M
Mike Stevenson
Hi. I'm in the process of re-learning all the C++ I forgot from
college, and I'm starting to get into some virgin (or at least only a
couple times) territory. I have some questions about casting a pointer
from a base class to a derived class. For example:
class Base{
public:
Base() {}
virtual ~Base() {}
void func1(int);
virtual void func2(int);
protected:
int foo;
};
class Deriv : public Base{
public:
virtual void func2(int);
void func3(int);
protected:
int bar;
};
So let's say I make a pointer thus: Base *ptr = new Deriv;. As I
understand it (please correct me if I'm wrong), ptr will use Base::func1
and have access to foo. Since it's defined as virtual, it knows to use
Deriv::func2. What I'm confused about is that ptr will not be able to
use func3 or access bar, saying that class Base does not contain those
things. I guess what I don't understand is, why bother casting the
pointer do the derived type when it can't access all its members?
What's the advantage over using Deriv *ptr = new Deriv?
Cheers,
Mike
college, and I'm starting to get into some virgin (or at least only a
couple times) territory. I have some questions about casting a pointer
from a base class to a derived class. For example:
class Base{
public:
Base() {}
virtual ~Base() {}
void func1(int);
virtual void func2(int);
protected:
int foo;
};
class Deriv : public Base{
public:
virtual void func2(int);
void func3(int);
protected:
int bar;
};
So let's say I make a pointer thus: Base *ptr = new Deriv;. As I
understand it (please correct me if I'm wrong), ptr will use Base::func1
and have access to foo. Since it's defined as virtual, it knows to use
Deriv::func2. What I'm confused about is that ptr will not be able to
use func3 or access bar, saying that class Base does not contain those
things. I guess what I don't understand is, why bother casting the
pointer do the derived type when it can't access all its members?
What's the advantage over using Deriv *ptr = new Deriv?
Cheers,
Mike