kaki novel
kaki novel

Reputation: 31

How to pass a derived class to function with base class as an arguement

I am still a beginner in programming and I am trying to pass an object from a derived class to a function with a base class as an arguement. But when I print the output, it would only print the attributs from the base class. Any atrributes which is in derived class won't come out. How to print it? Given this code:

#include<iostream>
#include<iomanip>
using namespace std;

int count=0;

class Person{
    private:
        string name;
        int age;

    public:
        Person(string n="NULL", int a=0)
        {
            name=n;
            age=a;
        }

        void printDetails(){
            cout<<endl<<"Name: "<<setw(50)<<name<<"Age: "<<setw(5)<<age;
        }

};


class Kid :public Person{
    private:
        string parentName;
    public:
        Kid(string n, int a, string pN) : Person(n,a)
        {
            parentName=pN;
        }

        void printDetails()
        {
            printDetails();
            cout<<" Parent Name : "<<setw(50)<<parentName;
        }
};

class Adult:public Person{
    private:
        string job;

    public:
        Adult(string n,int a,string j): Person(n,a)
        {
            job=j;
        }

        void printDetails()
        {
            printDetails();
            cout<<" Job Title   : "<<setw(50)<<job;
        }

};

class Copy{
    private:
        Person abc[3];
    public:
        void addPerson(Person a)
        {
            abc[count]=a;
            count++;
        }

        void print()
        {
            cout<<left;
            for(int i=0;i<3;i++){
                abc[i].printDetails();
            }
        }
};

int main()
{
    Copy test1;
    Adult p[2]={Adult("Zack",30,"Programmer"),Adult("Zim",26,"Engineer")};
    Kid kid("Michael",12,"Amy");

    test1.addPerson(p[0]);
    test1.addPerson(p[1]);
    test1.addPerson(kid);

    test1.print();
}

Upvotes: 2

Views: 181

Answers (1)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16057

When you assign a derived object to a base class object, only members of the base class are copied to the new object; it couldn't be any other way, if you think of it. This is called slicing.

If you, instead, store a pointer or reference to the derived object in a base class pointer, it still points or refers to the original object (this uses the fact that pointers to objects all look alike; all type hokus-pokus is only in our imagination, and that of the compiler).

In order to have the derived versions of member functions called through a base class pointer, you must declare the functions virtual. What you then get is a polymorphic class, which will expose exactly the behavior you would like to see here.

Upvotes: 5

Related Questions