-1

I am wondering if its possible to use a base class as parameter in function but when calling the function passing a derived class?

In .h file

class parent
{
    virtual void foo();
}

class child_a: parent
{
    void foo();
}

class child_b: parent
{
    void foo();
}

in main.cpp

void bar(parent p)
{ 
    // Doing things
}

int main()
{
    child_a a;
    bar(a);
    return 0;
}

Or do i have to use overloaded functions? it there another way to do it?

sskirren
  • 13
  • 3

1 Answers1

0

If you pass parameter by value, the copy contructor will be called so you will actually copy an object of type parent.

If you pass it by reference or pointer, you actually have a child class

class parent{
public:   
    parent(){
    }
    parent( const parent &obj){
        cout<<"I copy a parent"<<endl;
    }
};

class child : public parent{
public:
    child(){
    }    
    child( const child &obj){
        cout<<"I copy a child"<<endl;
    }
};

void foo(parent p){
    cout<<"I am in foo"<<endl;
}

int main()
{
   child c;
   foo(c);
}

Output:

I copy a parent

I am in foo

Gabriel
  • 3,564
  • 1
  • 27
  • 49