why does this result in a runtime error?

D

Dylan

thanks for any comments. Here's the code

//------------------------------------------------------------------

#include <iostream>
class Base
{
protected:

virtual int GetValue()=0;

public:

Base(){PrintValue();}


void PrintValue(){std::cout << GetValue();}
};


class Child : public Base
{
public:

int GetValue(){return 2;}
};


int main()
{

Child c;

return 0;
}
 
K

Karl Heinz Buchegger

Dylan said:
thanks for any comments. Here's the code

//------------------------------------------------------------------

#include <iostream>
class Base
{
protected:

virtual int GetValue()=0;

public:

Base(){PrintValue();}

void PrintValue(){std::cout << GetValue();}
};

class Child : public Base
{
public:

int GetValue(){return 2;}
};

int main()
{

Child c;

return 0;
}

Because of order of construction:
When Child gets constructed, first the Base part
of it gets constructed. That is: when the constructor
of Base runs, the Child object is not yet in existence
and thus the call to GetValue can only be resolved by
using the Base::GetValue. Unfortunately this function
is not implemented and thus the runtime error.

A simple rule to remember: During construction (and
destruction) of objects, the virtual mechanism is
not working.
 
D

Dylan

Thanks Karl

Because of order of construction:
When Child gets constructed, first the Base part
of it gets constructed. That is: when the constructor
of Base runs, the Child object is not yet in existence
and thus the call to GetValue can only be resolved by
using the Base::GetValue. Unfortunately this function
is not implemented and thus the runtime error.

A simple rule to remember: During construction (and
destruction) of objects, the virtual mechanism is
not working.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top