0
votes

I have 3 classes: the first a pure virtual base class base with derived classes derived1, derived2...

the second foo holds a smart ptr to a base class

the third holds a smart ptr to foo and has an overloaded member function which I want to depend on the derived class the ptr in foo points to.

Here is the working code

#include<iostream>
#include<boost/shared_ptr.hpp>

using namespace std;

class base{
public:
    base(){}
    ~base(){}
    virtual void FuncDer()=0;
};

class derived1 : public base{
    derived1(){}
    virtual void FuncDer(){
    cout<<"derived function1!"<<endl;
    }
};

class derived2 : public base{
    derived2(){}
    virtual void FuncDer(){
        cout<<"derived function2!"<<endl;
}
};

class foo {
public:
   foo();
    ~foo();
    boost::shared_ptr<base> get_base_ptr(){
        return base_obj;
    }
private:
    boost::shared_ptr<base> base_obj;
};

class bar {
public:
    bar();
    ~bar();
    void callfunc(){
    func(foo_ptr->get_base_ptr());
    }
private:
    boost::shared_ptr<foo> foo_ptr;
    void func(boost::shared_ptr<derived1>);
    void func(boost::shared_ptr<derived2>);
};


int main()
{
    cout<<"test"<<endl;

    return 0;
}

This however seems to fail with the error no matching member function. So my question is firstly is there something obviously wrong with this approach and secondly is there a more efficient / object oriented design approach which better deals with this type of problem.

1
Is it possible to have additional virtual function in derived classes that takes object of class bar as parameter, and to change bar::func functions into public?Dialecticus
Sorry for the delay I havent had the chance to look at this until now. I have now posted working code that reproduces my error.emza0114

1 Answers

0
votes

In principle this is the right way of doing it: Call the function on the base and polymorphism will do the right thing.

However, your code won't compile: The func definitions in bar aren't valid (at least I'm not sure what you intended them for - what are they supposed to implement?) and the func call in callfunc dereferences the pointer twice.

If you need concrete fixes, give the exact error.