-2

So I've started dabbling around a bit with base classes and derived classes, however, now that I'm getting into it seems that I've hit a wall. Basically, what I am want to do is assign an already initialized base class to a derived class. Reason for this being is that I'd like to access some variables of said base class in functions of my derived class.

I've came up with the following method of doing this:

class Bar
{
public:
    int Example = 16;
};

class Foo : public Bar
{
public:
    Bar* BarInstance;
    Foo(Bar* ClassInstance) : BarInstance(ClassInstance)
    {
    }

    int GetExample()
    {
        return BarInstance->Example; // Seems to work fine
    }
};

This seems to work fine, however I'd like to make this easier and just access it like this:

Foo* FooInstance = new Foo(this) // Where this is an instance of bar
int Output = FooInstance->Example; // Expected output is 16 (see above snippet of code)

Is this possible? I remember reading about a problem similar to this one, unfortunately I was not able to find it again. Any help is appreciated!

Teitoku42
  • 119
  • 10

1 Answers1

1

Just do this:

class Bar
{
public:
    int Example = 16;
};

class Foo : public Bar
{
public:
};

Foo* FooInstance = new Foo();
int Output = FooInstance->Example;

Due to polymorphism, the above snippet compiles and works perfectly fine. See it online


Foo already has everything that Bar has, because Foo is a Bar. Every Foo object initializes and stores a Bar object internally, and you have access to all of it's public and protected members via this pointer (it's also possible to access them implictly, without mentioning this - just like members of your own class).

You were trying to reinvent the wheel and recreate the polymorphism mechanism, without using the in-built polymorphism mechanism. While this is entirely possible, it's compilers' job, not yours (fortunately!)

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • Sorry, I didn't make it clear, but the Example variable being set to 16 by default is not what I intend to do with it. I'd like to do the following. 1. Initialize an instance of Bar. 2. Set Example of Bar to some value. 3. Initialize an instance of Foo with said instance of Bar. – Teitoku42 Aug 27 '19 at 18:41
  • 2
    @MisterGameboy Don't do that. You'd end up working against language to have features which are already in this language. Instead, you should create a constructor for `Foo`, which will have enough parameters to initialize `Bar` and [initialize `Bar` from `Foo` constructor](https://stackoverflow.com/questions/6923722/how-do-i-call-the-base-class-constructor). If `Foo` doesn't need its separate constuctor, you can even [inherit constructors of base class](https://stackoverflow.com/questions/347358/inheriting-constructors) to make it simpler. – Yksisarvinen Aug 27 '19 at 18:46