"Tony Johansson" <jo************ *****@telia.com > wrote in message
news:vC******** ***********@new sb.telia.net...
Hello!
Assume you have an abstract class called Body and a derived class called
cylinder.
When you have an abstract class you can't instansiate an object.
As you can see in the abstract class there are one data member called
density that you can't access because there will not be any object of
class Body. The data member density will be inheritated and all the member
functions.
So when you have an instance of class Cylinder and you access setDensity
you will access the density that is inheritated from Body.
Now to my question: When you can't access any data member in an abstact
class is it then any point to declare any data member in such class. Why
not just declare them in the derived class instead?
You certainly can access an abstract class's members and member functions.
The key is how you invoke the abstract ctor in the derived ctor's
initialisation list in order to generate a Cylinder instance.
Defining the abstract's pure-virtual member function(s) will save having to
provide that code in each derivative. The derived instance needs only call
the abstract base class's pure-virtual member functions with access
specifiers (ie: Body::getVolume ()). See getVolume() in Body and Cylinder
below...
The abstract class is no longer abstract once its been derived from and an
instance of the derived type is instantiated (abstract means "i can't exist
*unless* i'm inherited"). Also, nothing prevents you from defining the body
of a pure-virtual member-function (unlike Java's interface). The abstract
concept only applies to the instantiation of an abstract type itself. Not to
a derivative.
Note the output of the allocation invocations for Body and Cylinder.
Cylinder calculates the volume for the Body base using the Cylinder's ctor's
initialization list. Now its a tad easier to then derive from Body to create
a Block or Wedge class.
#include <iostream>
using std::cout;
using std::endl;
class Body
{
double density;
double volume;
public:
Body(double d, double v)
: density(d), volume(v) // init list
{
cout << "Body ctor invoked\n";
}
virtual ~Body()
{
cout << "Body d~tor invoked\n";
}
// member functions
double getDensity() const
{
return density;
};
virtual double getVolume() const = 0
{
return volume;
};
}; // abstract class Body
class Cylinder : public Body
{
double radie;
double length;
public:
Cylinder(double d, double r, double l)
: Body(d, 3.1416 * r * r * l),
radie(r), length(l) // init list
{
cout << "Cylinder ctor invoked\n";
}
virtual ~Cylinder()
{
cout << "Cylinder d~tor invoked\n";
}
// member functions
double getVolume() const
{
return Body::getVolume (); // by access specifier
}
}; // class Cylinder
int main()
{
// Cylinder(densit y, radius, length)
Cylinder cylinder(1.4, 8.0, 16.0);
cout << "density = " << cylinder.getDen sity();
cout << endl;
cout << "volume = " << cylinder.getVol ume();
cout << endl;
return 0;
}