C ++ inheritance by calling a given class function instead of its parent?

Really bad title, couldn't think of how to put it, sorry.

Let's say I had the following code:

class A {
    virtual int getSize() {
        return 0;
    }
}

class B : public A {
    int getSize() {
        return 32;
    }
}

void doStuff(A a) {
   std::cout << a.getSize() << std::endl;
}

int main() {
   B b;
   doStuff(b);
}

      

It will print 0

, however I want it to print 32

. In other words, I want to pass a class to it and it prints this class function, so I could create a class C

where the size is 64, and if I pass this C instance to the function doStuff

, I want it to print 64.

Is there a way to do this in C ++, do I need to use templates or some fancy C ++ feature that I am not aware of?

+3


source to share


3 answers


One byte patch:

void doStuff(A &a) {
  std::cout << a.getSize() << std::endl;
}

      



Your version takes an argument by value, which means the function makes a copy b

(the copy that is A

) and then calls the copy getSize()

. In this version, the function takes an argument by reference and calls b

its own one getSize()

, which is B::getSize()

.

+8


source


You should use pointers or even better: smart pointers! Thus, a function of the runtime type is called. This is a prime example of polymorphism. If you want to avoid pointers, the beta slicing approach would be equally valid.

#include <iostream>
#include <memory>

class A {
    virtual int getSize() {
        return 0;
    }
}

class B : public A {
    virtual int getSize() {
        return 32;
    }
}

void doStuff(std::shared_ptr<A> a) {
   std::cout << a->getSize() << std::endl;
}

int main() {
   std::shared_ptr<A> b(new B());
   doStuff(b); // Will output '32'.
}  

      



This should correctly call the function implemented by B.

+1


source


Object slicing is one approach, and besides, I think what you are asking for is, I think, a pretty simple use of polymorphism in C ++. http://www.cplusplus.com/doc/tutorial/polymorphism/

This applies almost immediately, just call the A Shape class and B and C can be square and triangular. The DoStuff function can take a pointer to a shape, then you can pass it a triangle or a square, and when you respect the shape in the function it will call the correct function.

So, you would have (and you, it seems to me, make public members):

class A {
public:
    virtual int getSize() {
        return 0;
    }
};

class B : public A {

public:
    int getSize() {
        return 32;
    }
};

void doStuff(A* a) {
    std::cout << a->getSize() << std::endl;
}

int main() {
    B b;
    doStuff(&b);
}

      

0


source







All Articles