By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,614 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

invoke sub-class's derived virtual method.

P: n/a
Hi,

I created a pure virtual class P and its derived sub-class D.
In class P, declared a pure virtural function pure(); in sub-class D
define its implementation.

eg.

class P
{
public:
P(P *p) { cout << p->pure(); }
virtual pure() = 0;
~virtual P() {}
}

class D: public P
{
public:
D():P(this) {}
pure() { cout << "derived method is called\n";
~D() {}
}

int main()
{
D *d = new D();
}

I would expect after compiled this program, it will print out the
following result:
"derived method is called"

But it tried to invoke the pure virtual function.
How can I correct this error? For some reason, I don't want to call
d->pure() in the main() function.

Thanks
Sam
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
sam++ wrote:
Hi,

I created a pure virtual class P and its derived sub-class D.
In class P, declared a pure virtural function pure(); in sub-class D
define its implementation.

eg.

class P
{
public:
P(P *p) { cout << p->pure(); }
virtual pure() = 0;
~virtual P() {}
}

class D: public P
{
public:
D():P(this) {}
pure() { cout << "derived method is called\n";
~D() {}
}

int main()
{
D *d = new D();
}

I would expect after compiled this program, it will print out the
following result:
"derived method is called"

But it tried to invoke the pure virtual function.
How can I correct this error? For some reason, I don't want to call
d->pure() in the main() function.

Thanks
Sam


Sorry, I just some syntax error. Please see the fixed version of the
above example. Just copy to your system and compile it with g++. The
program will invoke the pure virtual function, hence caused core dump.

#include <iostream>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

class P
{
public:
P(P *p) { p->pure(); }
virtual int pure() = 0;
virtual ~P() {}
};

class D: public P
{
public:
D():P(this) {}
int pure() { cout << "derived method is called\n"; }
~D() {}
};

int main()
{
D *d = new D();
delete d;
}
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.