0

I put some different structs that inherits from the same parent struct but when I try to access their members, compiler gives me an error. The code is this:

#include <bits/stdc++.h>

using namespace std;

struct A
{
    int a=0;
};

struct B:A
{
    int b=0;
};

struct C:A
{
    int c=0;
};

int main()
{
    vector<A> va;
    B bb;
    C cc;
    va.push_back(bb);
    va.push_back(cc);
    cout<<va[0].b;
    return 0;
}

The error is this:

'__gnu_cxx::__alloc_traits<std::allocator<A> >::value_type {aka struct A}' has no member named 'b'|

What could I do to solve this???

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
EdianBC
  • 1
  • 2
  • 1
    You're slicing the `bb` and `cc` to just the `A` part. Polymorphism and inheritance necessitate the use of pointers and references. Try a `vector>` instead. – Eljay Jul 01 '21 at 00:12
  • Obligatory link to [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – user4581301 Jul 01 '21 at 00:15
  • *What could I do to solve this???* -- I have to ask -- are you a Java or C# programmer trying to learn C++? In Java, you can do things like this, but not in C++. – PaulMcKenzie Jul 01 '21 at 00:19
  • @Eljay Thank you, I will investigate about that unique_ptr – EdianBC Jul 01 '21 at 06:21
  • @PaulMcKenzie Well I was a Competitive Programmer 2 years ago when I was in pre-universitary school (I think you call it high school) and all I used for competitions was C++. But then I moved to Unity and learned C# to try some game development. Now Im back in C++ learning just for fun, maybe I keep a few C# habits jaja. – EdianBC Jul 01 '21 at 06:31

0 Answers0