468,467 Members | 2,671 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,467 developers. It's quick & easy.

exception virtual function through base class

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
4 1361
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

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
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
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.

Similar topics

12 posts views Thread by Dario | last post: by
6 posts views Thread by Páll Ólafsson | last post: by
11 posts views Thread by Dave | last post: by
11 posts views Thread by santosh | last post: by
23 posts views Thread by TarheelsFan | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by kmladenovski | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.