Parameterized Constructor doubt...

Nov 26, 2011 at 1:56pm
Okay, so in my program, I have a class (say A)which has 5 int members. I want to use a parameterized constructor and set their default value to (say) 10, but at the same time, I want the user to be able to enter values of his own. For example, suppose there are two objects of class A, (say) a, & b, then if I use a.A(), then it calls the constructor, and lets the user enter 5 values, but IF I don't call it, say for b, and if I display the five ints of b, it should display 10's. So any way I can do this...? Please be simple in your explanation, as I have not completely grasped the idea of classes & OOP as such (a different matter altogether), and still am trying to learn as much as possible. Thank you in advance...
Nov 26, 2011 at 2:19pm
WHat you can do is overload your constructor. This means, make several constructors with different parameter lists. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyClass
{
private:
    int a;
    int b;
public:
    MyClass() // Default constructor
    {
        a = 10;
        b = 10;
    }
    MyClass(int a_, int b_) // Constructor that takes 2 int arguments
    {
        a = a_;
        b = b_;
    }
}

int main()
{
    MyClass Object1();
    MyClass Object2(2,4);
    return 0;
}


For more information on constructors see:
http://www.cplusplus.com/doc/tutorial/classes/
Last edited on Nov 26, 2011 at 2:21pm
Nov 26, 2011 at 2:19pm
You can have two constructors. One that takes no arguments and set all the members to 10. And another that takes 5 arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A
{
public:
	A() : i(10),j(10),k(10),l(10),m(10){}
	A(int i,int j,int k,int l,int m) : i(i)j(j),k(k),l(l),m(m){}
private:
	int i,j,k,l,m;
};

int main()
{
	A a; // all members are set to 10
	A b(1,2,3,4,5); // here we set the values explicit
}

Nov 26, 2011 at 2:25pm
Note that in Stewbond's code MyClass Object1(); is a function declaration and not an object.
Last edited on Nov 26, 2011 at 2:25pm
Nov 26, 2011 at 2:35pm
why dont u use a() instead of a.A()

#include<iostream>
using namespace std;
class A
{
int i1,i2,i3;
public:
A() //..........................................................................................................0
//A(int a=10,b=10,c=10) can also be used. ...............................1
{
i1=i2=i3=10;
}
void operator()() //......................................................................................2
{
cin>>i1>>i2>>i3;
}
};

int main()
{
A a,b;
b();
return 0;
}


//Play with 1 of this 3 things and ur wrk should be done........
Nov 26, 2011 at 5:10pm
Stewbond, yeah, I've already gone through everything this site has to offer, but my concept about classes is a bit weak, so....
Anyways, Thanks everyone! Helped a lot! :)
Topic archived. No new replies allowed.