What is the C ++ equivalent for java.lang.Object x = new Foo ()?

What is the C ++ equivalent java.lang.Object x = new Foo()?

+5
source share
3 answers

There is no equivalent to this in C ++, and it would be pointless to try to program Java in C ++. At the same time, I approach this in terms of attempts to imitate as much as possible the characterization and spirit of the assignment. Each method that I propose has disadvantages and limitations. The first two are not truly idiomatic C ++, but it is important to know about them in order to see what problems the last two solved.

1. C-style void pointers.

Let me start with the most basic and least useful void pointer:

void* foo = new Foo();

, void , .. void. : . -, ++ - . , . , , .

:

void* foo = some_function( _arg0 );

, , , . , , , , , , , , .

2. C-style Unions

N , , java.lang.Object, . , POD. : , , -POD-. , std::string.

, :

union myType{
    int a;
    char b[4];
};

char "b" "myType", int . ++ (, ..). ++.

3. Boost:: Any

, " ", Boost:: Any. , , . Boost , , . Any:

, ( , ) : , , , ++.

, void, .

4. ::

Boost:: Variant , . , -POD. , :

, ( Hen01 , , *). (, dynamic_cast, boost:: any_cast ..).

- :

  • Downcast . , downcast- .
  • . , , . , , , .

Edit:

, , , . .

+19

java.lang.Object x = new Foo(), ++ . , Object s, .

java.lang.Object x = new Foo() ++ Abstract Base Classes (ABC). ABC - , . ABC, -, :

class Object
{
public:
  virtual int my_func() = 0; // The "= 0" means "pure virtual"
};

Pure Virtual member (. * 1). ABC:

int main()
{
  Object obj; // not possible because Object is an ABC
}

ABC, - :

class Foo : public Object
{
public: 
  int my_func() { return 42; } // use of "virtual" is assumed here
};

Foo, :

int main()
{
  Object* my_obj = new Foo;
}

.. , shared_ptr.

Object Foo, slicing

int main()
{
  Foo my_foo;
  Object& obj_ref = my_foo; // OK
}

ABC. ABC, ( * 2). , delete undefined, .

   class Object
    {
    public:
      virtual int my_func() = 0;
    };
    class Foo : public Object
    {
    public: 
      int my_func() { return 42; } 
    };

    int main()
    {
      Object* obj = new Foo;
      delete obj;  // Undefined Behavior: Object has no virtual destructor
    }

, ABC , -, , . ABCs, , , , . IMO (debatable), ABC: dtor - dtor . , , , .


:


* 1) - . , , , . , , , , ; . :

class Object
{
public:
  virtual int my_funky_method() = 0;
  virtual bool is_this_ok() = 0 { return false; } // ERROR: Defn not allowed here
};

int Object::my_funky_method()
{
  return 43;
}

* 2) . , " , , "

+10

There is no equivalent, because Java allocates objects from a managed heap, C ++ allocates them in unmanaged memory. Objects in Java are automatically counted, while C ++ requires the explicit freeing of all memory.

The environments of the execution environment are fundamentally different from each other, while an analogy of a similar form looks like a trap.

+4
source

All Articles