Re: How to use a derived class with constructor
Angus <anguscomber@gmail.com> wrote in news:a0375667-103b-4cfe-b802-
3ea6d265f3f0@26g2000hsk.googlegroups.com:
Hello
I want to use polymorphic feature.
Eg if I had a base Shape class and a derived Circle class I could do
things like this:
Shape myShape;
MyCircle* pCircle = &myShape;
pCircle->SetValues(3,5);
cout << pCircle->area();
But my derived class has a constructor which gets passed variables.
Eg
Derived(int var1, std::string var2)
So how do I instantiate it?
I tried Derived* pDer(params);
This is actually backwards. Public inheritance provides an *isa*
relationship. A *Shape* isn't a Circle, but a circle is a shape.
So....
You could have:
class Shape
{
};
class Circle : public Shape
{
public:
void SetRadius(int r) {}
};
Circle c;
Shape * s = & c; // ok, Circles provide the functionality of a Shape
Shape s1;
Circle * c1 = & s1; // Not ok, Shape doesn't provide the
// functionality of a Circle.
The way constructors work for derivations is:
class base
{
int i;
public:
base (int x) : i(x) {}
};
class derived : public base
{
int x;
public:
derived(int x1, i1) : base(i1), x(x1) {}
};
As you can see from the example, the initialization list offers the
opportunity to specify a constructor for the base class so that the base
can properly initialize itself. Of course, this implys that the derived
class has to be able to come up with initialization values for the base
either by haveing equivalent parameters itself, or by being able to get
the required values in some other fashion.
joe