How to keep initial class object name? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to keep initial class object name?

So I learned a little technique to initialize a class with an object name and when I call the object of the derived it gives me 2 Mother constructors and destructors. Anyone know how I can keep the pre object names but prevent them from calling twice if preventable? Here's the code below. I'm still trying to figure it out but help is needed. #include <iostream> using namespace std; class Mother { public: Mother() { cout <<"Mother ctor"<<endl; } ~Mother() { cout <<"Mother dtor"<<endl; } } M; class Daughter: public Mother { public: Daughter() { cout <<"Daughter ctor"<<endl; } ~Daughter() { cout <<"Daughter dtor"<<endl; } } m; int main() { m; } /* outputs: Mother ctor Mother ctor Daughter ctor Daughter dtor Mother dtor Mother dtor */

24th Jan 2017, 7:20 PM
Travon
1 Answer
+ 1
The first 'Mother ctor' is from the object M, the second from m. They are separate objects, so each of them calls the Mother constructor once. Also the 'm;' in main has no effect.
24th Jan 2017, 7:44 PM
Robobrine
Robobrine - avatar