0

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;
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Psykocyber
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();

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.