Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
See more:
Hello everyone i'm having problems to understand the following behaviour. Maybe someone can explain this to me?
I have a base class like:

class BaseClass
{
    private:
        int _A;
        virtual void Initialize() = 0;
    public:
        BaseClass()
        {
           _A = 1;
           Initialize();
        }
}


And a derived class

class Child : public BaseClass
{
      public:
         Child() : BaseClass() {};
         void Initialize()
         {
              //do specific initialization here
         }
}


So what i'm expecting is, that when instantiating the Child class, the base class constructor gets called which uses the Initialize method implemented by the derived class.
What im getting is a linker error about the Initialize method.
But when using the Initialize method in an ordinary function it works as expected.
Posted

 
Share this answer
 
Comments
Legor 24-Mar-11 7:24am    
Thanks, that explains it perfectly.
Sergey Alexandrovich Kryukov 24-Mar-11 15:34pm    
This is important information, not apparent to the novice. (Also, one of the problems of C++ technology. I think we discussed that I have certain criticism about C++...). My 5.
--SA
Albert Holguin 24-Mar-11 16:22pm    
my 5!
HimanshuJoshi 24-Mar-11 16:25pm    
Important clarification. +5
Thats the normal behaviour.
* Constructor:
cannot call any virtual function because the derived class is not initialized. The state of the memebers is undefined.
* Destructor:
cannot call any virtual function because the derived class is already deinitialized. The member state is undefined or invalid from the final operations. Thats you must not set any values to a defined value (i.e. NULL).
Regards.

[edit]
additional (i forgot)
imagine you have classes like this:
class A{};
class B : public A{}
class C : public B{}


the functions for "class C" will be called as follows:

this->A::A();
this->B::B();
this->C::C();
// other code
this->C::~C();
this->B::~B();
this->A::~A();
 
Share this answer
 
v3
Comments
HimanshuJoshi 24-Mar-11 16:25pm    
Nice answer. +5
Legor 25-Mar-11 5:07am    
Thanks again for the clarification

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