-2
class Base{

public:
    virtual void func2() const{
        cout << "1" << endl;
    }

    virtual void func1(Base temp){
        cout << "Class 1" << endl;
        temp.func2();
    }

};
class Derived : public Base{
public:

    void func2() const{
        cout << "2" << endl;
    }
    void func1(Base temp){
        cout << "Class 2" << endl;
        temp.func2();
    }

};

int main(){
    Base one;
    Derived two;

    two.func1(two);
    cout << "------------\n";


    return 0;
}

Output is:

Class 2

1

So my question is: why when I'm giving func1(two) an object of Derived, it is not calling on virtual func2 that outputs 2. The compiler is always choosing func2() that is defined in the Base class.

It does, however, chooses func2 in the Derived class when you call on it, i.e. two.func2(); which outputs 2

Thy Gamosh
  • 77
  • 1
  • 7

3 Answers3

3
func1(Base temp)

That is copying your object, it is not your original Derived but a Base instance copy initialized from the derived.

func1(Base& temp) should work

Mario Corchero
  • 5,257
  • 5
  • 33
  • 59
1

It's because you pass an argument by value: func1 param is Base temp, not Base &temp. So you construct a new, temporary object of class Base, so you call Base::func2() which prints 1.

CiaPan
  • 9,381
  • 2
  • 21
  • 35
1

you should try with:

virtual void func1(Base& temp){
        cout << "Class 1" << endl;
        temp.func2();
    }

this will prevent copying the object, preserving the hierarchy.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115