473,789 Members | 2,931 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Where to put attribute when using Inheritance

Hello!!

Assume we have one base class called Vehicle and two derived classes called
Car and Bus.
I would be able to call method getName on an object of class Car or Bus and
return back the name that is set for this class. Asking getName on an object
of class Vehicle is of no interest. Assume we have an attribute called name
of type string.

Now to my question do you think it's right to put the name attribute in each
of class Car and Bus. I think so.
I think putting the name attribute in class Vehicle is wrong because the
name is different in class Car and Bus.

The name attribute is set in the c-tor for class Car and Bus.
This getName is made pure virtual so polymorfism can be used to call the
right getName depending of the object type

I'm I right in my thoughts.

Many thanks
//Tony


Jul 23 '05 #1
3 1974
Tony Johansson wrote:
Assume we have one base class called Vehicle and two derived classes called
Car and Bus.
Why are you starting another thread instead of continuing in your previous
"Weapon / Winchester / .." one? You're asking same questions. Did you
read the replies to your first post?
[...]

Jul 23 '05 #2
In my opinion you want three things:
- Have Vehicle objects with a private member 'name'
- Have derived objects from Vehicle - which have a name
- No objects of Vehicle can be created

I would solve this by making the constructor of vehicle not accesible
to the outside world and have the name attribute at the highest
possible level, see a quick example below. If you try to add a line
like 'Vehicle v;' to the main() you get a compilation error.

-#include <iostream>
-#include <string>
-
-using namespace std;
-
-class Vehicle
-{
- string m_name;
-protected:
- Vehicle() {};
-public:
- virtual ~Vehicle() {};
- const string& name() {return m_name;}
- void name(const string& n) { m_name = n; }
-};
-
-class Car:public Vehicle
-{
-public:
- Car(const string& n):Vehicle(){ name(n); }
- ~Car() {}
-};
-
-int main()
-{
- Car c("Fiat");
- cout << c.name() << endl;
-
- return 0;
-}

Jul 23 '05 #3

"Tony Johansson" <jo************ *****@telia.com > wrote in message
news:lJ******** ***********@new sb.telia.net...
Hello!!

Assume we have one base class called Vehicle and two derived classes called Car and Bus.
I would be able to call method getName on an object of class Car or Bus and return back the name that is set for this class. Asking getName on an object of class Vehicle is of no interest. Assume we have an attribute called name of type string.

Now to my question do you think it's right to put the name attribute in each of class Car and Bus. I think so.
I think putting the name attribute in class Vehicle is wrong because the
name is different in class Car and Bus.
Nothing prevents you to support a common attribute and a specialized
attribute.

The name attribute is set in the c-tor for class Car and Bus.
This getName is made pure virtual so polymorfism can be used to call the
right getName depending of the object type

I'm I right in my thoughts.

Many thanks
//Tony


Yes, your choice to place the name attribute in each derived class is an
option. Placing a common attribute in the abstract class is another option.
Same goes for an Engine class. Its a different Engine but its still an
Engine.

Since name isn't a clear attribute, lets consider a common license number
attribute for all vehicles. Let Cars have a car-type attribute and Trucks a
truck-classification attribute. I can implement the pure-virtual display()
member function, overload display() in both Car and truck and still call the
abstract display() through an access specifier.

// CarTest.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;

class Vehicle
{
std::string m_license;
protected:
Vehicle(std::st ring s) : m_license(s) { }
public:
virtual ~Vehicle() { }
virtual void display() const = 0
{
cout << "vehicle license: " << m_license;
cout << "\t";
}
};

class Car : public Vehicle
{
std::string m_type;
public:
Car(std::string s, std::string t) : Vehicle(s), m_type(t) { }
~Car() { }
void display() const
{
Vehicle::displa y();
cout << "car type: " << m_type;
cout << endl;
}
};

class Truck : public Vehicle
{
std::string m_classificatio n;
public:
Truck(std::stri ng s, std::string t) : Vehicle(s), m_classificatio n(t)
{ }
~Truck() { }
void display() const
{
Vehicle::displa y();
cout << "truck classification: " << m_classificatio n;
cout << endl;
}
};

int main()
{
std::vector<Veh icle*> v_vehicles;

v_vehicles.push _back(new Car("M1111", "sportscar" ));
v_vehicles.push _back(new Truck("G2222", "2 Tons"));
v_vehicles.push _back(new Car("L3333", "coupe"));
v_vehicles.push _back(new Truck("D4444", "4 Tons"));

typedef std::vector<Veh icle*>::iterato r ITER;
ITER it = v_vehicles.begi n();
for ( it = v_vehicles.begi n(); it != v_vehicles.end( ); ++it)
{
(*it)->display();
}

for ( it = v_vehicles.begi n(); it != v_vehicles.end( ); ++it)
{
delete *it;
}

return 0;
}

Jul 23 '05 #4

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

Similar topics

4
1870
by: Maarten van Reeuwijk | last post by:
Hello, Maybe I was a little too detailed in my previous post . I can boil down my problem to this: say I have a class A that I encapsulate with a class Proxy. Now I just want to override and add some functionality (see my other post why). All functionality not defined in the Proxy class should be delegated (I can't use inheritance, see other post). It should be possible to achieve this using Python's great introspection possibilities,...
1
1408
by: Skip Montanaro | last post by:
I just stumbled upon a bug in some group-written code. We have this sort of class hierarchy: class X(object): ... class A(X): def __init__(...): self.attr = 0.0
6
2486
by: Alex Hunsley | last post by:
I know that I can catch access to unknown attributes with code something like the following: class example: def __getattr__(self, name): if name == 'age': return __age else: raise AttributeError
3
2222
by: TruongLapVi | last post by:
Hi everybody, I have write customize attribute TestAttribute public class TestAttribute : Attribute { private string name; public TestAttribute(string name) {
2
9691
by: belgie | last post by:
Whereas in Asp I could submit my form contents to any other Asp page, it appears that in Asp.NET the primary Asp form will only submit to itself. I have tried changing the Action attribute in the Form tag, but it changes itself back when compiled. I have also tried changing the form Action attribute in client-side javascript prior to submitting the form, but I get this error: The View State is invalid for this page and might be...
46
2515
by: clintonG | last post by:
Documentation tells me how but not when, why or where... <%= Clinton Gallagher http://msdn2.microsoft.com/en-us/library/saxz13w4(VS.80).aspx
5
3675
by: crystalattice | last post by:
I've finally figured out the basics of OOP; I've created a basic character creation class for my game and it works reasonably well. Now that I'm trying to build a subclass that has methods to determine the rank of a character but I keep getting errors. I want to "redefine" some attributes from the base class so I can use them to help determine the rank. However, I get the error that my base class doesn't have the dictionary that...
2
2589
by: Paul McGuire | last post by:
On May 25, 8:37 am, Michael Hines <michael.hi...@yale.eduwrote: Here's a more general version of your testing code, to detect *any* diamond multiple inheritance (using your sample classes). -- Paul for cls in (A,B,C,D): seen = set()
5
1478
by: Rafe | last post by:
Hi, I've been thinking in circles about these aspects of Pythonic design and I'm curious what everyone else is doing and thinks. There are 3 issues here: 1) 'Declaring' attributes - I always felt it was good code practice to declare attributes in a section of the class namespace. I set anything that is constant but anything variable is set again in __init__():
0
9511
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
10200
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
10139
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,...
0
9020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7529
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
6769
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.