Hi

I'm having a problem with this piece of inheritance code. When compiling it displays this error
" 'getAverage' : is not a member of 'Person' "
but shouldn't the casting overcome that problem?
Do i really need to have a virtual function in "Person" for this to work?

Thanks

#include <iostream>
#include <list>
#include <vector>
#include <string>

using namespace std;

class Person {
public:
	Person(char name[], int newage);
	virtual string* getName(){return &name;}
	int getAge(){return age;}
	virtual void setName(char name[]){this->name = name;}
protected:
	string name;
	int age;
};

Person::Person(char name[],int  newage){
	age = newage;
	this->name = name;
}

class Student : public Person{
private:
	float average;
public:
	Student(char name[], int age, float average);
	float getAverage(){return average;}
	void setAverage(float average){this->average = average;}
};

Student::Student(char name[], int age, float newaverage) : Person(name, age){
	Person::Person(name,age);
	average = newaverage;
}

int main(){
	Person *p = new Student("John", 50, 10); 
	cout << (dynamic_cast <Person*>(p))->getAverage();

	cout << "\nPress enter to exit";
	cin.ignore(std::cin.rdbuf()->in_avail() + 1);
	return 0;
}

>> cout << (dynamic_cast <Person*>(p))->getAverage(); Look what are you doing. You are casting a Person pointer with Person only. What is the effect?

change it to cout << (dynamic_cast <Student*>(p))->getAverage();

Stupid me... anyway, thanks for the help :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.