default Ctor

why we need default ctor while passing by value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class test{
private:
 int number;
public:
 test(int i)
 {
   number = i;
 }
};

class useTest
{
private:
 test mobj;
public:
 useTest(test1 _obj)// reference is better choice
 {
   mobj = _obj;
 }
};

void main()
{
 test testobj(10); // Work all fine
 useTest * obj = new useTest(testobj); // will fail, ask for defaut ctor
}
The compiler will provide a generic default constructor unless you specify any constructor for the class.

For test, you are providing a constructor, so the compiler no longer automatically gives you a default ctor.

Therefore... objects of type test cannot be default constructed.


You are attempting to default construct a 'test' object here:

1
2
3
4
5
6
7
8
9
10
11
12
class useTest
{
private:
 test mobj;  // <- useTest owns a 'test' object here

public:
 useTest(test1 _obj)
    // <- but you do not explicitly construct it here, so 'mobj' is default constructed
    //    since there is no default constructor for mobj, you get the error
 {
   mobj = _obj;
 }



If you don't want to provide a default constructor for test, you must explicitly construct 'mobj' in your useTest class:

1
2
3
4
5
 useTest(test1 _obj)
   : mobj( _obj )   // <- do this
 {
    //mobj = _obj;  // <- instead of this
 }


Here, it is copy-constructing mobj. Whereas in your code it was default constructing, then assigning.
Since you are passing by value, a new test object is being created and then copied to (separately, and in that order) whenever the useTest constructor (line 16) is invoked.

void main() is not C++; use int main() and be sure to return a number.
Last edited on
Passing by value doesn't really matter... as he'd have the same problem if he was passing by reference.

But +1 @ the void main garbage.
Thanks Disch and Branflakes1093

Disch, so it is mandatory to have default ctor when we pass object by value and dont use Initialization Lists?
Disch, so it is mandatory to have default ctor when we pass object by value and dont use Initialization Lists?


Passing by value has nothing to do with it. It's all about how the owned object (in this case 'mobj') is constructed.

'mobj' has to be constructed. If you do not explicitly construct it with an initializer list... it will be default constructed. If there's no default constructor, that's a compiler error.

Case in point.. attempting to default construct useTest would also fail:

1
2
3
4
5
6
7
8
9
10
class useTest
{
private:
 test mobj;
public:
 useTest() // <- default constructor
   // <- ERROR because we're trying to default construct 'mobj'
 {
 }
};
Topic archived. No new replies allowed.