Search code examples
c++classshared-ptrmember

cpp: can't get the value of member via pointer by using ->


I have a question about how to use the -> in cpp. What I need to do is get the private member value code of class B by using a pointer a created in class C, my code has a structure like this: I paste the original code here:

//detector.hpp
class Detector{
public:
  std::string name;
  int code;
}

//detectorH.hpp
class detectorH : public Detector {
private:
  std::string name;
  int code;
public:
  detectorH();
std::shared_ptr<Detector> h_detector();
}

//detectorH.cpp
detectorH::detectorH(){
  name = "h";
  code = 1111;
}
std::shared_ptr<Detector> h_detector(){
  return std::make_shared<detectorH>();
}

//findCode.cpp
class findCode{
private:
  std::vector<std::shared_ptr<Detector>> detectors;
public:
  findCode(){
   detectors.push_back(h_detector());
  void find(){
   for(auto& d:detectors){
     std::cout << d->code << std::endl;
   }
  }
 }
};

But the problem is the cout is always 0, meaning that I've failed to get the right value. I don't know why...and there is no bug message so I don't know how I can fix it... Anyone can give my a hint? Thanks a lot!


Solution

  • As commenters said - code in A has nothing to do with code in B. Moreover when you access code via pointer to A you access A::code. As we don't really know what you want to achieve you can for example remove code from B:

    class A {
    public:
        int code;
    };
    
    class B : public A {
    public:
        B() { code = 1111 };
    };
    

    or initialize it to some value:

    class A {
    public:
        A() : code{ 2222 } { }
        int code;
    };
    
    class B : public A {
    public:
        B() : code{ 1111 } { }
    private:
        int code;
    };
    

    You can do it also in B's constructor:

    class B : public A {
    public:
        B() : code{ 1111 } { A::code = 2222; }
    private:
        int code;
    };