-1

To describe my problem, I will assume that we have:

  1. abstract class Base (with few pure virtual functions).
  2. classes A, B and C. All inherited from Base. All override pure virtual functions from Base.

Now the problem is in ways to create vector, that can store any of A, B or C object. Well, I know, that I need to create vector of pointers to base class object, like:

std::vector<Base*> list;

But my friend with Apple M1 and clang able to create vector of base class objects (without using pointer) and all fine in his environment. Code:

std::vector<Base> list;

It is very strange for me. I was assuming, vector store objects with equal size per each of them. So all objects in vector must be of the same type, and with pointer all fine, but how it works with instances?

  • You can create a `vector`, no problem. Other than the constraint that it can only hold `Base`, and not any derived classes from `Base`. (Trying to put a derived class into it will result in *slicing*.) – Eljay Mar 17 '22 at 20:54
  • I am agree. But he able to put there instances of derived classes. So, i am confused. – Ilya Bezrukov Mar 17 '22 at 20:57
  • Anything that is derived from `Base` has an is-a relationship with `Base`, meaning that `A`, `B` and `C` all have `Base` object as part of them. Your friend using `std::vector` is doing [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing) – NathanOliver Mar 17 '22 at 20:59
  • Does object slicing work if there is pure virtual function in parent class? – Ilya Bezrukov Mar 17 '22 at 21:06
  • It shouldn't since you cannot create object of types that have pure virtual functions. Example: http://coliru.stacked-crooked.com/a/f676175fb44840c5 – NathanOliver Mar 17 '22 at 21:11
  • 3
    Your friend has at least one mistake, and probably more that are helping hide the mistake. We'd need to see their code to pinpoint exactly what they screwed up. – user4581301 Mar 17 '22 at 21:13
  • I just have seen your example, @NathanOliver. And this output is what I get, if trying to make same things as my friend. – Ilya Bezrukov Mar 17 '22 at 21:56
  • 1
    I will make clean, minimal and reproducible example and append in my question. – Ilya Bezrukov Mar 17 '22 at 22:01
  • Well, it is our mistake. We didn't notice, that in his code virtual functions are not pure virtual, just with empty definition. – Ilya Bezrukov Mar 18 '22 at 17:06

1 Answers1

0

I checked this situation on clang and M1 again and checked code of my friend. I have found a problem place, he didn't actually define pure virtual functions, just empty virtual functions in Base class, like here:

class Base {
public:
    virtual void function() {}
}

In this case, object slicing works fine, because we can instantiate Base class. And, of course, we also able to create vector of Base class objects and put there objects of derived class.

std::vector<Base> list;
A a;  // A class here is derived from Base
list.push_back(a);