1

i have this function :

void f(const A& a){a.print()};

and a class:

class A { 
void print() const{cout<<"a"<<endl;}
}

in the first section i want my code to print b using inheritance without changing the print function. i tried implementing new class B which inherits from A . and my code printed b. now in the second section i need to change only this line : void f(const A& a) and my code should print a. how can i do so?

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

class A{
protected:
    string a;
public:
    A(string a):a(a){}
    virtual void print()const{
        cout<<"a"<<endl;
    }
    virtual ~A(){}

};
class B:public A{
    //string b;
public:
    B(string b):A(b){}
    virtual void print()const{
        cout<<"b"<<endl;
    }
    virtual ~B(){}

};
void f(const A& a){
    a.print();
}
int main(){
    B a=B("b");
    f(a);
    return 0;
};
Mykola
  • 3,343
  • 6
  • 23
  • 39
wanhu
  • 13
  • 1
  • 5

3 Answers3

0

You can get this effect by passing the parameter by value

void f(A a);

That way the function will receive a copy of the A part of any class derived from A.

This is sometimes done by mistake (see What is object slicing?), but gets the job done here.

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

if you want to avoid the virtual call, you need a new object of type A...

you can use pass the parameter by value or create a copy of type A inside the function f:

void f(const A& a) {
    A tmp(a);
    tmp.print()
}
0

You can indeed copy the base class subobject as described in other answers. But you don't need to and it usually makes more sense to use static dispatch:

a.A::print();

Of course, this modifies a line other than the declaration of the function.

eerorika
  • 232,697
  • 12
  • 197
  • 326