Creating Objects in C ++ Conditional Expressions

let's say I want to instantiate an object of a different type depending on certain circumstances, so I would instantiate them inside the body of an if statement. The problem is that if you want to use this object later, you need to declare it before creating it. How to declare a shared object. Is there something similar to an object class in Java?

I did some google searches, such as "generic object C ++" and "object class C ++", and it looks like it is not.

+3
source share
6 answers

Unlike Java, C ++ does not have a "mother" object from which all classes are inherited. To accomplish what you are talking about, you will need to use the base pointer of your own class hierarchy.

Animal* a;
if (...) a = new Cat();
else if (...) a = new Dog();

In addition, since there is no garbage collection, it is better to use smart pointers when you do such things. Otherwise, do not forget to remember delete a. You must also make sure that it Animalhas a virtual destructor .

+3
source

This problem can be solved using interfaces. C ++ now knows no 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 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

, , X.

( - Base, , , , # Java. , , , .. ++, . , .)

+4

++ " ". .

stakx, , . - . , ? , . , .

, , boost::any. () . , , , . , Derived *, boost::any_cast<Derived *>(wrapped), - boost::any_cast<Base *>(wrapped) .

+2
std::shared_ptr<Base> X( some_condition ? new A() : new B() ); 
+1

++ , , void *, .

, , , , :

class A {};
class B {};

class MyBase
{
    // Define the interface that you need.
};

class MyA : public MyBase
{
private:
    A a;
public:
    // Implement MyBase in terms of A.
};

class MyB : public MyBase
{
private:
    B b;
public:
    // Implement MyBase in terms of B.
};

int main ()
{
    MyBase* base = 0;
    if (useA)
        base = new MyA();
    else
        base = new MyB();
}
0

. :

Derived1 d1;
Derived2 d2;
Base * b = 0;

if (useD1) {
  b = &d1;
} else {
  b = &d2;
}

, . , , . - , .

0
source

Source: https://habr.com/ru/post/1772234/


All Articles