A pointer to class C can point to an object of class C. (No
surprise)
Car *cptr;
cptr = new
Car;
.... it can also point to an object of any subclass of
C.
class HybridCar : public
Car {
};
Car *cptr;
cptr = new HybridCar;
But not vice versa. A
pointer to a class SubC cannot point to a superclass object.
class HybridCar : public
Car {
};
HybridCar *hcptr;
hcptr= new Car; // won't compile!
Assignment
statements and subclasses
class Account
{
private:
double balance;
};
class NamedAccount:
public Account {
private:
char name[MAX];
};
Account acc;
NamedAccount nacc;
acc = nacc; //
slicing
nacc = acc; // not
allowed
Back to cars ....
Car *cptr;
cptr = new HybridCar;
Pointer
type is ..... Car
Object type is ..... Hybrid
Car
When we tell
it to do something (accelerate / getFuelEfficiency/
etc.)
will it behave like a Car (pointer type) or a Hybrid Car (object
type)?
Functions declared as virtual behave according to the object
type.
Functions
not declared as virtual behave according to the ptr type.