Home > Enterprise >  C passing data from object of class A to object of derived class B
C passing data from object of class A to object of derived class B

Time:10-13

For the sample code below, I'm trying to pass (or attribute, if that suits you better) the data from object of class A to the object of derived class B. What I don't understand so far, is how do I transfer the data from the parent class object, to the derived class object.

The "code" below expresses how I've tried to do that.

class Foo{
 protected:
 string Name, Surname;
 public:
 void readData()
 {
  cin >> Name >> Surname >>;
 } 
 }

class Bar : public Foo
{
 public:
 Bar (Foo a)
{ 
 Name = Name;
 Surname = Surname;
}
 void printData()
 {
 //code
 }
}

int main()
{
 Foo a;
 a.readData();
 Bar b(a);
 b.printData()
}

CodePudding user response:

Minimal changes to make your code compile is using Foos copy constructor and simply access the inherited members in Bar::printData:

#include <string>
#include <iostream>

class Foo{
 protected:
 std::string Name, Surname;
 public:
 void readData()
 {
  std::cin >> Name >> Surname;
 } 
 };

class Bar : public Foo
{
 public:
 Bar (const Foo& a) : Foo(a) {  }
 void printData()
 {
    std::cout << Name << " " << Surname;
 }
};

int main()
{
 Foo a;
 a.readData();
 Bar b(a);
 b.printData();
}
  • Related