0

For a concrete example, say I am given

vector<shared_ptr<DClass>> cVector

and DClass (which is derived from MyClass) has the following interface

class DClass: public MyClass {
  public:
    DClass( string id, string name, int p, int v )
      : MyClass id, name, p ), var1_ ( v ) {}
    int GetDClassVar1() const { return var1_; }
  private:
    int var1_;
};

and MyClass (which DClass inherits from) has the following interface

class MyClass {
  public:
    MyClass( string id, string name, int p )
      : id_( id ), name_( name ), myclassvar1__( p ) {}
    string GetMyClassID() const { return id_; }
    string GetMyClassName() const { return name_; }
    int GetMyClassVar1() const { return myclassvar1__; }
    virtual int GetDClassVar1() const { return 0; }
  protected:
    string id_;
    string name_;
    int myclassvar1_;
};

How can I call upon the GetDClassVar1 function using cVector assuming that cVector is populated?

***EDIT I try using

cVector.at(1).GetDClassVar1.() 

and I get the error

const value_type’ {aka ‘const class std::shared_ptr<MyClass>’} has no member 
named ‘GetDClassVar1'
dcjboi
  • 31
  • 6

2 Answers2

0

How can I call upon the GetDClassVar1 function using cVector assuming that cVector is populated

for (const auto& d : cVector)
    std::cout << d->GetDClassVar1() << "\n";

Note that when calling a member function that is not const-qualified, you need to remove the const before auto&. For a single element:

cVector.front()->getDClassVar1();
cVector.at(42)->getDClassVar1();

This syntax is due to the fact that std::shared_ptr has an overloaded operator -> member function that forwards to the underlying pointer.

Also note that you want polymorphic base classes to have a virtual destructor, see here.

lubgr
  • 37,368
  • 3
  • 66
  • 117
0

To access the members of a pointer, you have to use -> instead of .. Other than that, it's pretty much the same!

int result = cVector[0]->GetDClassVar1();

Alternatively, you could dereference it first:

int result = (*cVector[0]).GetDClassVar1();

Or bind it to a reference, if you're doing multiple operations on it:

auto& element = *cVector[0];
int result = element.GetDClassVar1(); 
Alecto Irene Perez
  • 10,321
  • 23
  • 46