C++, How to Call a Constructor Directly, Without New

C++, is it possible to call a constructor directly, without new?

Sort of. You can use placement new to run the constructor using already-allocated memory:

 #include <new>

Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor

new (&ooo[0]) Object1("I'm the 3rd object in place of first");

So, you're still using the new keyword, but no memory allocation takes place.

Calling constructors in c++ without new

Both lines are in fact correct but do subtly different things.

The first line creates a new object on the stack by calling a constructor of the format Thing(const char*).

The second one is a bit more complex. It essentially does the following

  1. Create an object of type Thing using the constructor Thing(const char*)
  2. Create an object of type Thing using the constructor Thing(const Thing&)
  3. Call ~Thing() on the object created in step #1

How to call constructor without new?

You can use cast operator to implicitly:

    sealed class Student
{
public string Name
{
get;
private set;
}

Student()
{
}

public static implicit operator Student(string name)
{
return new Student
{
Name = name
};
}
}

Then you can do Student student = "Sabrina";.

Why explicitly call a constructor in C++

Most often, in a child class constructor that require some parameters :

class BaseClass
{
public:
BaseClass( const std::string& name ) : m_name( name ) { }

const std::string& getName() const { return m_name; }

private:

const std::string m_name;

//...

};

class DerivedClass : public BaseClass
{
public:

DerivedClass( const std::string& name ) : BaseClass( name ) { }

// ...
};

class TestClass :
{
public:
TestClass( int testValue ); //...
};

class UniqueTestClass
: public BaseClass
, public TestClass
{
public:
UniqueTestClass()
: BaseClass( "UniqueTest" )
, TestClass( 42 )
{ }

// ...
};

... for example.

Other than that, I don't see the utility. I only did call the constructor in other code when I was too young to know what I was really doing...

Can constructor call another constructor in c++?

Not before C++11.

Extract the common functionality into a separate function instead. I usually name this function construct().

The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.

A destructor, however, can be called without a problem.

Calling a constructor without creating object

You're not explicitly calling the constructor, instead this code creates a temporary unnamed object with type Demo, which is destroyed immediately after ;.

Yes, memory is allocated (automatically, on the stack) for this temp object and it's freed (again automatically) after ;. Meanwhile, the constructor and destructor are called, as expected.

Is a constructor a function and is it possible to call a constructor

Formally in the C++ Standard it is (along with several others) a special member function so yes it is a function, but it is a special function and not all of the normal rules apply.

There is no syntax to write code that calls a constructor directly or forming a function pointer to it. The Standard specifically says "Constructors do not have names."

The compiler will automatically call a constructor when an object is created. The compiler will also automatically call constructors for subobjects (bases and members) of a class object. "Delegating constructors" are sort-of a degenerate case of initialization of subobjects (In formal algebra, we say that any set is a subset of itself, and say "strict" subset when we mean a subset that is not the entire set).

There are a variety of ways to create an object and some of them look like a function call, but that's actually a cast and results in creation of a new object, on which the constructor is called implicitly by the compiler. There's also placement-new syntax which doesn't do very much besides causing the compiler to implicitly call the constructor -- but even there a brand new object is being created.

One important way in which the compiler's implicit call to a constructor differs from an explicit function call found in user code is that the implicit call occurs within an implicit try/catch scope that will result in destruction of subobjects if an exception occurs. A direct call to the constructor, if one were possible, wouldn't have such extra behavior.



Related Topics



Leave a reply



Submit