Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does parentheses directly after a class name create a new instance?

// 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)?

like image 214
sungeng Avatar asked Sep 23 '15 13:09

sungeng


Video Answer


1 Answers

  1. 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).

  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.

like image 82
SingerOfTheFall Avatar answered Oct 06 '22 14:10

SingerOfTheFall