954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Pointer to inherited class problem

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;
}

Psykocyber
Newbie Poster
5 posts since Nov 2007
Reputation Points: 10
Solved Threads: 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();

siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,486
Solved Threads: 140
 

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

Psykocyber
Newbie Poster
5 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You