mercredi 24 juin 2015

Avoiding object slicing and using shared_ptr

Now I'm developing a searching node program. My code is below and I actually want to search a specific child node. To avoid object slicing, I used a pointer, but the pointer is null_ptr maybe. So how should I avoid this problem. I'm not sure its problem? And to avoid new instance attribute, Parent obj instance in main() should be declared as shared_ptr supported since c++11?

#include <iostream>

 using namespace std;

 class Parent {
   public:
     Parent() { name = "Parent"; }
     virtual void print() {
       cout << "Parent::print()" << endl;
     }

     string name;
 };

 class Child1 : public Parent {
   public:
     Child1() { name = "Child1"; }
     virtual void print() override{
       cout << "Child1::print()" << endl;
     }
 };

 class Child2 : public Parent {
   public:
     Child2() { name = "Child2"; }
     virtual void print() override{
       cout << "Child2::print()" << endl;
     }
 };

 class Manager {
   public:
     void getChild(int i, Parent* obj) {
       if(i==0) {
         cout << "sest child1" << endl;
         obj = (&child1);
       } else {
         cout << "sest child2" << endl;
         obj = (&child2);
       }
     }
     Child1 child1;
     Child2 child2;
 };

 int main()
 {
   // object slicing?
   // Parent obj;
   // Manager manager;
   // manager.getChild(1, obj);
   // obj.print();

   Parent* obj;
   Manager manager;
   manager.getChild(1, obj);
   obj->print();

 }

My code is broken because of segmentation fault.

  $ a.out D
    sest child2
    [1]    5457 segmentation fault  ./work/derived/a.out D

Aucun commentaire:

Enregistrer un commentaire