I have one base class and a derived class with a static member variable in the base:
Then in a code file, I have:Code:class A{ private:static int i; string myname;public:A(); void inc(); int getI() const;}; class B:public A{ public:B();};
And finally, in main I have:Code:int A::i=0; void A::inc(){i++;} int A::getI(){return i;} A::A(){inc(); myname = "A";} B::B(){inc(); myname = "B";}
The result is:Code:A a1; std::cout << "i_val for class a1 is: " << a1.getI() << std::endl; A a2; std::cout << "i_val for class a2 is: " << a2.getI() << std::endl; B b1; std::cout << "i_val for class b1 is: " << b1.getI() << std::endl; B b2; std::cout << "i_val for class b2 is: " << b2.getI() << std::endl;
I was expecting the numbers to be in sequential order: 1, 2, 3, 4. Instead, I discovered that when instantiating B, the constructor for A was invoked as well which is why the "i" value is incrementing by 2.Code:i_val for class a1 is: 1 i_val for class a2 is: 2 i_val for class b1 is: 4 i_val for class b2 is: 6
So my question is, is there a way to make sure that the constructor for B and B only is invoked when I instantiate B?
If not, does that mean every base constructor is invoked if you instantiate a derived class? And what would be advantage of this?
I did try declaring the constructor as virtual, but the compiler wasn't buying that (so now I know you cannot declare constructors as virtual).



LinkBack URL
About LinkBacks




CornedBee