user2487364
user2487364

Reputation: 11

Pointer to an object with explicit constructor

I am trying to do something like this and I keep getting an error:

class A {
public:
    explicit A();
}

A * a = new A(); //results in:  undefined reference to A()

I also tried:

A * a = A(); //results in cannot convert A to A * in assignment

Is there a way to do this? I would greatly appreciate the help.

Upvotes: 1

Views: 356

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126562

In the first case, the problem is not related with the fact that the constructor is explicit, but with the fact that you have declared it and not defined it. What you are getting is an error from the linker, not from the compiler. Try this:

 class A {
 public:
     explicit A() { /* Or anything more meaningful than just doing nothing */ }
 };

In the second case, that won't work. First, because you're trying to initialize a pointer (i.e. a variable of type A*) from an object of type A. Second, because even if you did the slightly more meaningful:

A a = A();

That won't compile because explicit constructors are not considered for copy-initialization (the form of initialization that uses the = sign).

Upvotes: 1

Tyler Jandreau
Tyler Jandreau

Reputation: 4335

You're not providing the body of the constructor. Try:

class A {
public:
    explicit A() {}
}

The explicit keyword just means that it prevents type conversions, which is what the second error is saying.

Upvotes: 0

Related Questions