class Vector
{
private:
double* elem; // pointer to the elements
int sz; // the number of elements
public:
// Constructor: Acquire resources.
Vector(int s)
{
elem = newdouble[s];
sz = s;
// Initialize elements.
for (int i = 0; i < sz; ++i)
elem[i] = 0;
}
/// ...
}; /// class
Note that the ctor takes 1 arg.
As expected, if you try to declare an instance of the Vector class without specifying 1 arg, you will get a compilation error:
Vector v; /// gives compilation error
However, now consider the following class VectorContainer, which wraps the Vector class:
1 2 3 4
class VectorContainer
{
Vector v; /// OK - no compilation error !
}
I'm aware that the problem would occur when the ctor is included in VectorContainer.
My question really was why the problem doesn't occur when the ctor is not included. Hence I used the term "declaration" rather than "definition" of the var in question.
class Vector
{
public:
Vector(int s) {}
};
class VectorContainer
{
Vector v; // -> this is a declaration just saying that
// -> VectorContainer has a member named v, of type Vector
// -> there is no object creation or storage allocation
// -> this is essentially a description
// -> this is what @moschops pointed out
};
int main()
{
Vector v(3); // -> this is both a declaration and definition
// -> this means an object will be created
// -> a region of memory, the right size and type will be
// -> this memory will be referred to as v in this scope
// -> to create this object the constructor Vector(int) is invoked
Vector v1; // -> just like above, except there's no constructor Vector()
// -> so compilation fails, as we have tried to call a function
// -> that does not exist
extern Vector v2; // -> declaration only, no storage is allocated no constructor is called
// -> compilation succeeds, v2 must be properly defined elsewhere
// -> before use
VectorContainer v3; // -> fails for same reason as line 24
// -> when it tries to initialise its v member.
return (0);
}
@SSteven it appears you've been caught out by the fact that if the compiler can figure it out, it will make a definition not a declaration
My question really was why the problem doesn't occur when the ctor is not included.
Why would it? What did you ask the compiler to do that it doesn't know how to do? What function did the linker go looking for that it couldn't find?
The problem will occur when you try to use a constructor that doesn't exist. Your code doesn't try to use a constructor that doesn't exist, so there is no problem. That's why the problem does not occur. Because code not existing is only a problem when you try to use the code that doesn't exist.
You can declare functions (such as constructors) that don't exist all day long without any trouble. The problem only happens when you try to use (i.e. execute) functions that don't exist.