exception virtual function through base class

V

voidtwerp

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;
};
 
T

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
 
M

Murali Krishna

voidtwerp said:
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
 
V

voidtwerp

Murali said:
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.
 
P

Pete Becker

voidtwerp said:
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)
 

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
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top