Search code examples
c++classoopderived-class

How to get base object's data in a new derived object?


(Beginner in OOP.) I have a person class which stores the name of the person. In a derived class instance printer, I need that name so that I can do further tasks with it.

#include <iostream>
#include <string>
class Person{
  public:
  std::string name;
};

class Printer: public Person{
  public:
  void print(){
      printf("%s", this->name.c_str());  
  }
};
int main() {
    Person one;
    one.name = "john";
    Printer printer;
    printer.print();
    return 0;
}

What am I not doing to have printer see the data in one ? I'd be having several printer-like objects so storing "john" only once is the goal here.


Solution

  • You have made the member vars public but this is not the right approach for the OOP, the right one is to have them under private access specifier and use setters and getters.

    Now to your mistakes:

    1. You use void for main but with c++ you can only use int for it.

    2. You use std::string as an argument for printf but it can't accept it. (I passed the c_string of the std::string to correct that).

    3. You use an object, from the parent class, and give it a name then use another object, from the driven one, to print the name of the first one. (I used only one)

    #include <iostream>
    #include <string>
    
    class Person{
    public:
        std::string name;
    };
    
    class Printer: public Person{
    public:
        void print(){
            printf("%s",this-> name.c_str());
        }
    };
    int main() {
        Printer printer;
        printer.name = "name";
        printer.print();
    }
    

    After your comments, I have updated Printer class to do your inttent

    #include <iostream>
    #include <string>
    class Person{
    public:
        std::string name;
    };
    
    class Printer{
    public:
        void print(const Person& person ){
            printf("%s", person.name.c_str());
        }
    };
    int main() {
        Person one;
        one.name = "name";
        Printer printer;
        printer.print(one);
    }