16.7 DEALING WITH NAME CONFLICTS FOR DATA MEMBERS


16.7 DEALING WITH NAME CONFLICTS FOR DATA MEMBERS

Let's consider the hierarchy shown in Figure 16.12 in which all the data members have the same name, called name. This data member has a different meaning in each class. In the class Alien, it stands for an Alien's name. In the class CatLovingAlien, it stands for a cat's name. In the class DogLovingAlien, it stands for a dog's name. Given that PetLovingAlien inherits the name fields of the same name from twodifferent paths, each carrying a different meaning, we are faced with the problem of how to assign proper values to these fields in a PetLovingAlien constructor. This problem looks more difficult that it actually is. All we have to do is to ship off the different arguments in the PetLovingAlien constructor to the different superclass constructors, as shown below:

      PetLovingAlien(string catName, string dogName, string ownerName)          : CatLovingAlien(catName, ownerName),            DogLovingAlien(dogName, ownerName),            Alien(ownerName) {} 

Each superclass constructor will make sure that its own name data member gets the value that is assigned to it.

click to expand
Figure 16.12

The other problem with data-member name conflicts is how to access such data members in the class where the name conflicts occur. Let's say we need access to both the cat's name and the dog's name, in addition to possibly the owner's name, in an object of type PetLovingAlien. This is easily taken care of by using the ‘::' operator, as shown in lines (A), (B), and (C) of the example below.

 
//NameConflictDataMem.cc #include <iostream> #include <string> using namespace std; class Alien { protected: string name; public: Alien (string nam) : name(nam) {} }; class CatLovingAlien : virtual public Alien { protected: string name; // Cat's name public: CatLovingAlien(string catName, string ownerName) :Alien(ownerName), name (catName) {} }; class DogLovingAlien : virtual public Alien { protected: string name; // Dog's name public: DogLovingAlien(string dogName, string ownerName) : Alien(ownerName), name(dogName) {} }; class PetLovingAlien : public CatLovingAlien, public DogLovingAlien { public: PetLovingAlien(string catName, string dogName, string ownerName) : CatLovingAlien(catName, ownerName), DogLovingAlien(dogName, ownerName), Alien(ownerName) {} void print() { cout << CatLovingAlien::name << " " //(A) << DogLovingAlien::name << " " //(B) << Alien::name << endl; //(C) } }; int main() { PetLovingAlien alien("Tabby", "Pluto", "Zaphod"); alien.print(); // Tabby Pluto Zaphod return 0; }




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net