473,799 Members | 3,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheritance and abstract classes

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?

class Body
{
public
virtual ~Body(){}
virtual const double getVolume() const = 0;
virtual const double getArea() const = 0;
double getDensity();
void setDensity(doub le);

private:
int density;
};

class Cylinder : public Body
{
public:
virtual const double getVolume();
virtual const double getArea();

private:
double radie, length;
};

//Tony
Jul 23 '05 #1
4 2310
Because all classes you want to derive from Body have a density
attribute?

Jul 23 '05 #2
Tony Johansson wrote:
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.
Right.
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.
Well, each Cylinder is also a 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.
Yes.
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?
A good thing about deriving from a class is that you inherit members so you
can put everything in the base class that is shared between all classes
derived from it. This is also true in this case. If every class derived
from Body has a density, why put it in each class separately? Just put it
once in the base class, and all the others inherit it.
Consequently, if each derived class has its own getDensity() and
setDensity(), you cannot call those functions through a pointer or
reference to Body, since Body doesn't have them. You'd always need to know
the right class and cast to that class.
class Body
{
public
virtual ~Body(){}
virtual const double getVolume() const = 0;
virtual const double getArea() const = 0;
double getDensity();
void setDensity(doub le);

private:
int density;
};

class Cylinder : public Body
{
public:
virtual const double getVolume();
virtual const double getArea();

private:
double radie, length;
};

//Tony


Jul 23 '05 #3

"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;
}
Jul 23 '05 #4
"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?

class Body
{
public
virtual ~Body(){}
virtual const double getVolume() const = 0;
virtual const double getArea() const = 0;
double getDensity();
void setDensity(doub le);

private:
int density;
};


Now everybody who uses Body as a base class has to use your implementation
of getDensity(). What do you care how it's implemented? An abstract class
should be abstract: no constructor, no data items, and no non-virtual
methods. Of course sometimes you would like to provide a partial
implementation as a convenience. But you can have your cake and eat it too:

class Body
{
public: // note the colon
virtual ~Body() {}
virtual double getVolume() const = 0; // no need for const double
virtual double getArea() const = 0;
virtual double getDensity() const = 0; // should be const method
};

class BaseBody : public Body
{
private:
double m_density;
public:
BaseBody(double i_density=0.0) : m_density(i_den sity) {}
void setDensity(doub le i_density) {m_density = i_density;}
virtual double getDensity() const {return m_density;}
};

Now your client can use BaseBody if he is satisfied with your implementation
but can also derive directly from Body.

[snip]

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
3294
by: John Perks and Sarah Mount | last post by:
Trying to create the "lopsided diamond" inheritance below: >>> class B(object):pass >>> class D1(B):pass >>> class D2(D1):pass >>> class D(D1, D2):pass Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
2
1493
by: He Shiming | last post by:
Hi, I've got a question regarding class inheritance. The following code reproduces the problem I'm dealing with: class IBase { public: virtual void Method(void)=0; };
20
10089
by: km | last post by:
Hi all, In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? thanks in advance for enlightment ... here's the snippet #!/usr/bin/python
20
23114
by: Steve Jorgensen | last post by:
A while back, I started boning up on Software Engineering best practices and learning about Agile programming. In the process, I've become much more committed to removing duplication in code at a much finer level. As such, it's very frustrating to be working in VBA which lacks inheritance, one of the more powerful tools for eliminating duplication at the level I'm talking about. I've recently come up with a technique to emulate one...
14
12922
by: Steve Jorgensen | last post by:
Recently, I tried and did a poor job explaining an idea I've had for handling a particular case of implementation inheritance that would be easy and obvious in a fully OOP language, but is not at all obvious in VBA which lacks inheritance. I'm trying the explanation again now. I often find cases where a limited form of inheritance would eliminate duplication my code that seems impossible to eliminate otherwise. I'm getting very...
7
1747
by: shintu | last post by:
Hi, For the following code snippet, the compiler complains for "mi *mi1=new mi;" statement //******************************************************* #include <iostream> using namespace std; class base{ public :
4
1476
by: vivekian | last post by:
Hi, Have this following hierarchy which am implementing for a networking program. The base class 'ASocket' is the base class from which 'AListener' and 'ATalker' inherit . None of the functions in the derived classes would override functions from the base class. The derived classes would extend the base class. A couple of doubts : 1. Should the functions in the base class be declared virtual ?
60
4948
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the 'target' programming community herein) to get some community input and verify (or not) the following two statements. Few programmers (3 to7%) UNDERSTAND 'Strategic Functional Migration
2
1870
by: Heinz Ketchup | last post by:
Hello, I'm looking to bounce ideas off of anyone, since mainly the idea of using Multiple Virtual Inheritance seems rather nutty. I chalk it up to my lack of C++ Experience. Here is my scenario... I have 5 Derived Classes I have 3 Base Classes
2
2624
by: mmcgarry.work | last post by:
Hi, I would like to follow Stroustrup's advice of separating an object interface (abstract class) from an object implementation (concrete class), See Section 15.2.5 in Stroustrup 3rd Edition. Specifically, I want to create an abstract base class that defines an object interface: class myAbstractClass
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10484
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.