Code and Stuff

Nov 10, 2011

C++: Instantiation & Function Declaration

Single class

Given a class A with a default constructor, the following code:
A a();
is a declaration of a function that returns an object of type A and takes no arguments. You will get a compilation error when you try to call a method on a or pass it to some other method/function. To create an instance of A you have to avoid the brackets and simply use
A a;

2 classes

In addition to the simple class A, lets define also a class B as follows:
struct B {
   B(const A& a) {}
};

Just as in the example above,

B b1(A());
B b2(A);
declares 2 functions. The first returns an instance of B and takes, as parameter, a function with no inputs and which returns A. The second also returns B, but has a parameter of type A.

To create an instance of B with a temporary default constructed instance of A you will have to wrap the creation of the temporary instance with round brackets.

B b1((A()));

No comments: