template pattern question

S

s

I want to make a baseclass with a constructor and destructor and have
these call methods in the derived classes which vary. I though the
'template' pattern looked appropriate and tried the following, which
doesn't compile and I'm not sure why. The error message is self-
explanatory:

abstract virtual 'virtual void IClass::init()' called from constructor

but clearly I have then misunderstood the template pattern
implementation; what would be correct? why doesnt the baseclass
constructor call to init() delegate to the derived class?


#include <iostream>

class IClass{
public:
IClass(){
init();
}
protected:
virtual void init()=0;
};

class Class1:public IClass{
public:
Class1(){
//nop
}

virtual void
init(){
std::cout<<"template method class 1"<<std::endl;
}
};

int main (int argc, char * const argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
IClass * ic=new Class1();
return 0;
}
 
S

SG

I want to make a baseclass with a constructor and destructor and have
these call methods in the derived classes which vary.
Why?

I though the
'template' pattern looked appropriate and tried the following, which
doesn't compile and I'm not sure why. The error message is self-
explanatory:

abstract virtual 'virtual void IClass::init()' called from constructor

but clearly I have then misunderstood the template pattern
implementation; what would be correct? why doesnt the baseclass
constructor call to init() delegate to the derived class?

See C++ FAQ 23.5

Cheers!
SG
 
J

Juha Nieminen

s said:
why doesnt the baseclass
constructor call to init() delegate to the derived class?

You can't call a derived class function from the constructor of the
base class because at that point the derived part has yet not been
constructed (effectively it "doesn't exist" at that point).
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top