Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiation of objects in conditionals c++

Tags:

c++

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.

like image 963
joedillian Avatar asked Dec 22 '22 21:12

joedillian


2 Answers

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.

like image 37
Charles Salvia Avatar answered Jan 04 '23 09:01

Charles Salvia


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.)

like image 123
stakx - no longer contributing Avatar answered Jan 04 '23 09:01

stakx - no longer contributing