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

exception virtual function through base class

P: n/a
The following code cant call derived::fn() , it is calling base::fn()
which is pure virtual.
(the same problem is ocurring if I do it outside of constructors also)
What am I doing wrong here?

class base
{
public:
virtual void fn(void)=0;
};

class derived
{
public:
void fn(void){};
};

class user
{
public:
user(){
derived d;
p=(base*)new derived();//What is wrong here?
if(p!=0)
p->fn();//exception because p->fn == 0
}
private:
base *p;
};

Jul 6 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
TB
voidtwerp skrev:
The following code cant call derived::fn() , it is calling base::fn()
which is pure virtual.
(the same problem is ocurring if I do it outside of constructors also)
What am I doing wrong here?

class base
{
public:
virtual void fn(void)=0;
};

class derived
class derived : public base
{
public:
void fn(void){};
};

class user
{
public:
user(){
derived d;
p=(base*)new derived();//What is wrong here?
if(p!=0)
p->fn();//exception because p->fn == 0
}
private:
base *p;
};

--
TB @ SWEDEN
Jul 6 '06 #2

P: n/a

voidtwerp wrote:
The following code cant call derived::fn() , it is calling base::fn()
which is pure virtual.
(the same problem is ocurring if I do it outside of constructors also)
What am I doing wrong here?

class base
{
public:
virtual void fn(void)=0;
};

class derived
{
public:
void fn(void){};
};

class user
{
public:
user(){
derived d;
p=(base*)new derived();//What is wrong here?
if(p!=0)
p->fn();//exception because p->fn == 0
}
private:
base *p;
};
you haven't inherited the base class.
p=(base*)new derived();//What is wrong here?
same as above. base and derived are two different classes with no
relation

-- Murali Krishna

Jul 6 '06 #3

P: n/a
Murali Krishna wrote:
>
you haven't inherited the base class.
doh! thanks to TB and Murali for your quick responses - how I managed
to do that in both the original problem and the posted version without
spotting it I dont know.

Jul 6 '06 #4

P: n/a
voidtwerp wrote:
Murali Krishna wrote:
>>you haven't inherited the base class.


doh! thanks to TB and Murali for your quick responses - how I managed
to do that in both the original problem and the posted version without
spotting it I dont know.
The cast was a clue. (I missed it, too, on my first reading)
Jul 6 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.