Let's say I have a base class of shapes shape and two derived classes square and circle. Now I would like to have a function where the shape is not specified

double foo(shape S)
{
return getArea;
}

but which prints the area of a square when calling

square sq();
foo(sq);

and the area of a circle when calling

circle cr();
foo(cr);

Thus, I declared a virtual function in the base class (returning only 0) and the appropriate virtual functions in the two derived classes. However, when calling foo with either a square or circle object I always get the result of the base class. How to do it properly?


EDIT:

Now the code is working, here a simple example. The solution is indeed to pass the object from the shape class (derived or not) by reference. This allows to define a generic function which accepts all kind of derived objects:

#include<iostream>

using namespace std;


class shape
{
public:
  shape (double L_par): L(L_par){};
  double getL(){return L;}
  virtual double getArea(){return 0;}

private:
    const double L;
}; 
class square: public shape
{
public:
  square (double L_par): shape(L_par),area(L_par*L_par){cout<<"square with area="<<area<<endl;};
   virtual double getArea(){return area;}

private:
    const double area;
};
class circle: public shape
{
public:
  circle (double L_par): shape(L_par),area(3.1415*L_par*L_par){cout<<"circle with area="<<area<<endl;};
  virtual double getArea(){return area;}

private:
const double area;
};

void foo(shape &shp)
{
  cout<<"L="<<shp.getL()<<endl;
  cout<<"area="<<shp.getArea()<<endl;
}

int main(int argc, char* argv[])
{
  double L=4;
  square sq1(L);
  circle cr1(L);

  foo(sq1);
  foo(cr1);
  cout<<sq1.getArea()<<endl;
  cout<<cr1.getArea()<<endl;
  return 0;
}
有帮助吗?

解决方案

You are passing the shape by value:

double foo(shape S) { .... }

This means the function has a copy of only the shape part of the object. This is called object slicing. You can fix this by passing a reference:

double foo(const shape& S) { .... }

其他提示

Dynamic binding through C++ is implemented using references and pointers. Therefore your function foo should take a reference to shape;

double foo(shape &s) {
    return s.getArea(); //your virtual function?
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top