Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using inherited containers

Status
Not open for further replies.

jimbo1999

Programmer
Mar 11, 2003
11
GB
Hi,

I've created a class SetOfPersons which holds an array of Person object pointers (Person ** elements;)

I've also created a subclass - SetOfAdults which inherits from SetOfPersons. Also I have an Adult class that inherits from Person.

In my main method I have:
Adult *a1 = new Adult("Name", 98); //constructor is (name, age).
SetOfAdults adults;
adults.add(*a1);

Later I try:
Adult & a2 = adults.getNextElement();

The compiler gives me:
cannot convert from 'class Person' to 'class Voter &'

Where am I going wrong? Should the SetOfPersons be modified?

Thanks,
jimbo.
 
First, main() is a global function, a method must be a member of a class.

Second, I'll assume that getNextElement() returns a Person, but you must realize that a Person is not necessarily an Adult. If you want to use polymorphism, you should have it return a pointer to a Person instead, and then just type cast it to an Adult*.

Third, this isn't Java - functions should use Pascal casing in C++.
 
Is class Voter derived from class Adult?
How are your classes inherited (i.e. in the header code)?
 
Sorry, should read Adult, not voter.

I have:
class Person {...}
class Adult : public Person{...}

then
class SetOfPersons {...}
and class SetOfAdults : public SetOfPersons {...}

Is there a way to convert a Person reference to an adult reference when it is returned from SetOfAdults? Because all I get returned at the moment is a Person reference.
 
I don't think you can convert a reference that way. If it was a pointer instead of a reference, you could use either dynamic_cast<> or static_cast<> to convert from Person* to Adult*. Use dynamic_cast<> if RTTI is enabled and you're not sure whether or not the Person is really an Adult. If you're sure it is an adult, use static_cast<> instead.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top