1

This is my code

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
 using namespace std;

 int professorCounter = 0;
 int studentCounter = 0;

class Person{
public:
    string name;
    int age;

};

class Professor : public Person{
 public:
    int publications;
    int cur_id;

    Professor(){
        professorCounter++;
        this->cur_id = professorCounter;
    }
    void getdata(){
        cin >> this->name >> this->age >> this->publications;
    }
    void putdata(){
        cout << this->name << " " << this->age << " " << this->publications                 << 
     endl;
     }
 };

 class Student : public Person{
public:
    int marks[6];
    int cur_id;
    Student(){
        studentCounter++;
        this->cur_id = studentCounter;
    }
    void getdata(){
        cin >> this->name >> this->age;
        for(int i=0; i<6; i++){
            cin >> this->marks[i];
        }
    }
    void putdata(){
        cout << this->name << " " << this->age;
        for(int i=0; i<6; i++){
            cout << " " << this->marks[i];
        }
    }
  };
 int main(){

int n, val;
cin>>n; //The number of objects that is going to be created.
Person *per[n];

for(int i = 0;i < n;i++){

    cin>>val;
    if(val == 1){
        // If val is 1 current object is of type Professor
        per[i] = new Professor;

    }
    else per[i] = new Student; // Else the current object is of type Student

    per[i]->getdata(); // Get the data from the user.

}

for(int i=0;i<n;i++)
    per[i]->putdata(); // Print the required output for each object.

return 0;
}

I have a pointer array of type Parent Class(Person) and each of it's pointer is pointing to the child class (Professor, Student) I want to access the child (i.e. student and Professor) using the pointer of Parent which is pointing to the child

i am this to setData

  per[i]->getdata(); // Get the data from the user.

and this to print data

  per[i]->putdata(); // Print the required output for each object.

But it shows error saying " ‘class Person’ has no member named ‘getdata’ " and " ‘class Person’ has no member named ‘putdata’ "

Hacker Rank question link : https://www.hackerrank.com/challenges/virtual-functions/problem?h_r=next-challenge&h_v=zen&isFullScreen=true

Aditya
  • 13
  • 2
  • 1
    `per[n];` is invalid in C++, `n` must be known at compile-time. C++ is statically typed language - `Person` does indeed not have any of those methods. Are you looking for `virtual` methods? Please do not learn a language by doing hacker rank puzzles, it will teach you all the bad habits, pick up a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. Please do not use `new`, use smart pointers, or do not use pointers at all. – Quimby Aug 22 '21 at 09:39

0 Answers0