1

Let's say i have two class named Object (base class) and an actor class (derived class). The actor class uses physics so i need to implement it on the Actor class. But there are other derived class of the "Object" class that don't use physics so i don't want to have physics implemented on them because it would be useless data.

class Object
{
    public:
    Object();
    ~Object();

    virtual void Main();

    private:
    Transform transform;
};

class Actor : public Object
{
    public:
    Actor();
    ~Actor();

    void Main();

    private:
    Physics physics; //Can i make this????
};

Because i only implemented physics on the actor class i need to upcast it from some way to the base class like this:

int main()
{
    Object* BaseClass = new Actor;
}

Is the "physics" data, defined on the actor, allowed to be upcasted even if i don't want to use it externally? There isn't any way i can make it?

  • 1
    Don't use the name Object as a name of a class as it tends to confuse things with the base class Object in languages as Java and C#. I do not know if it is allowed in c++, but it is not really a good name. That does not take anything away from your question though. – Bent May 7 '16 at 17:01
3

In your example the instance Object* BaseClass = new Actor(); gives you an object about which all you know is that it can do what another instance of Object can do.

The instance itself has all the knowledge of an Actor.

If you call a method on BaseClass (say a method called ToString()) it will be an Actor.ToString() not a Object.ToString() you call.

If the ToString() method of an Actor instance uses any information specific to the Actor class that would be used even if you call it only knowing that it is an Object.

1

Objects don't generally participate in up-casts, whether implicit or explicit up-cast.

For one, the upcast is applied to the reference to the object, and for another, up-casts are validated at compile time so there is no runtime behavior for a valid up-cast (and an invalid one won't compile).

This means that when accessed via a reference as an Object type, the actual object is still an Actor and will have all the Actor data and behaviors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.