Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
1)Below program is working but no constructor is called for derived2.
#include<iostream>

using namespace std ;
class drived1;

#define SIZE 10

class base
{
public:
int a;
drived1* get_value_object_drived1();

base()
{
cout << "Base Ctor" << endl;
}

};

drived1* base::get_value_object_drived1()
{
a = 20;
return reinterpret_cast<drived1*>((this));
}

class drived1: public base
{
public:
int b;
void displayD1()
{
cout << "drived1 displayD1 is called" << endl;
b = 10;
}

drived1()
{
cout << "drived1 Ctor" << endl;
b = 5;
}


};

class drived2: public base
{
public:
int d_buff[SIZE];

drived2()
{
cout << "drived2 Ctor" << endl;
}

};

void main()
{
base B;
drived2 D2;

D2.get_value_object_drived1()->displayD1();

}

But below one is not working when returning object instead of pointer.
#include<iostream>

using namespace std ;
class drived1;

#define SIZE 10

class base
{
public:
int a;
drived1 get_value_object_drived1();

base()
{
cout << "Base Ctor" << endl;
}

};

drived1 base::get_value_object_drived1()
{
a = 20;
return reinterpret_cast<drived1>((*this));
}

class drived1: public base
{
public:
int b;
void displayD1()
{
cout << "drived1 displayD1 is called" << endl;
b = 10;
}

drived1()
{
cout << "drived1 Ctor" << endl;
b = 5;
}


};

class drived2: public base
{
public:
int d_buff[SIZE];

drived2()
{
cout << "drived2 Ctor" << endl;
}

};

void main()
{
base B;
drived2 D2;

D2.get_value_object_drived1().displayD1();

}


What I have tried:

1)First program is working but no constructor is called for derived2. Why is constructor not called for derived2.
2)But 2nd program is not working when returning object instead of pointer of same type.
Posted
Updated 29-Oct-20 10:31am
v2

Error in 2nd program
Error 3 error C2027: use of undefined type 'drived1'
Error 4 error C2079: 'base::get_value_object_drived1' uses undefined class
Error 5 error C2440: 'reinterpret_cast' : cannot convert from 'base' to 'drived1'
 
Share this answer
 
No constructor is called because you don't construct an instance of the class.
You allocate a variable that can contain a instance of it:
C++
void main()
    {
    base B;
    drived2 D2;
    ...
    }
But that doesn't create any instances. To create an instance you need the new keyword:
C++
void main()
    {
    base B;
    drived2 D2 = new drived2();
    ...
    }
 
Share this answer
 
Comments
markkuk 1-Nov-20 5:52am    
You're confusing C++ with Java.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900