let's say I want to instantiate a different type of object depending on certain circumstances, so i would instantiate them inside the body of an if statement. The problem is if you want to use that object later, you need to declare it before instantiation. How does one declare a generic object. Is there something similar to the object class in Java?
I've done some google searching like "generic object c++" and "object class c++" and there doesn't appear to be something like that.
Unlike Java, C++ has no "mother" object which all classes inherit from. In order to accomplish what you're talking about, you'd need to use a base pointer of your own class hierarchy.
Animal* a;
if (...) a = new Cat();
else if (...) a = new Dog();
Also, because there's no garbage collection either, it's better to use smart pointers when you do this sort of thing. Otherwise, be sure you remember to delete a
. You also need to make sure that Animal
has a virtual destructor.
This problem can be solved with interfaces. Now, C++ doesn't know interfaces, but you can easily do something similar with abstract base classes:
class Base { ... }
class A : public Base { ... } // A is a Base
class B : public Base { ... } // B is a Base
...
Base *X; // that's what you will end up using
if (some_condition)
X = new A(); // valid, since A is a Base
else
X = new B(); // equally valid, since B is a Base
This will require you to put common functionality into the base class so that you can actually perform operations on X
.
(If you derived all your classes from something like Base
, you'd end up with a super-class like it's available in e.g. C# or Java. However, in my opinion, generic programming, ie. templates in C++, have much reduced the need for a super-class like that. I'd wager that you'll be able to find better code designs in most cases.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With