// in a.h
#include <iostream>
#include <vector>
typedef std::vector<double> Array;
class A
{
public:
A(int n);
private:
Array m;
};
//in a.cpp
#include "a.h"
A::A(int n)
{
m = Array(n, 0.0);
}
I want to initialize m in the constructor of A. Is the expression of parentheses with some parameters directly after the class name (std::vector<double>
) legal?
And what's is the difference between
Array m(n,0.0)
and
m=Array(n,0.0)
?
Yes it is legal. ClassName()
calls the constructor of that class.
Note: Technically, a constructor doesn't have a name, so it can't be found during the name lookup, so ClassName()
is really an explicit type conversion using the functional notation which _results in_ calling the constructor (as per c++ standard 12.1.2).
Array m(n,0.0)
creates a variable m
of a class Array
by calling Array
's constructor that accepts 3 parameters.
MyClass m = Array(n,0.0)
creates an unnamed variable of a class Array
by calling Array
's constructor with 3 parameters, and then copies that unnamed variable into m
, but most likely the compiler will optimise that thanks to copy elision. However, if you changed that to MyClass m; m = Array(n,0.0)
, a constructor followed by assignment operator will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With