Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Generate standard constructor

I often find myself writing very simple classes instead of C-style structs. They typically look like this:

class A
{
public:
  type mA;
  type mB;
  ...
  A(type mA,type mB,...) : mA(mA),mB(mB),... {}
}

Is that a sensible way of doing things? If yes, I was wondering whether there was any third party plugin out there or any handy short cut to automatically construct the text for the constructor (e.g. take the highlighted or existent member definitions, replace semicolons with commas, move everything on the same line, ...)? Thanks

like image 859
Cookie Avatar asked Jul 26 '11 14:07

Cookie


People also ask

How do you define a default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Can we create constructor in C?

A Constructor in C is used in the memory management of C++programming. It allows built-in data types like int, float and user-defined data types such as class. Constructor in Object-oriented programming initializes the variable of a user-defined data type. Constructor helps in the creation of an object.

Does compiler create default constructor?

In C++, the compiler creates a default constructor if we don't define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members. However, in Java default constructors assign default values.

Can we provide one default constructor for our class?

Yes, a constructor can contain default argument with default values for an object.


1 Answers

Yes, just use plain aggregates:

struct A
{
  type mA;
  type mB;
  ...
};

Usage:

A x = { mA, mB, ... };

An aggregate has no custom constructors, destructor and assignment operator, and it allows for plenty of optimisations. Aggregate initialization with the brace syntax for example usually constructs the members in place without even a copy. Also you get the best possible copy and move constructors and assignment operators defined for you by the compiler.

like image 60
Kerrek SB Avatar answered Oct 31 '22 07:10

Kerrek SB