Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor using {a,b,c} as argument or what is {a,b,c} actually doing?

I know, that I can initialize data like this.

int array[3] = { 1, 2, 3 };

or even

int array[2][2] = { {1, 2}, {3, 4} };

I can also do it with std::vector

std::vector<int> A = { 1, 2, 3 };

Let's say I want to write my own class:

class my_class
{
     std::vector< int > A;
     public:
     //pseudo code
           my_class(*x) { store x in A;} //with x={ {1, 2}, {3, 4} }
     // do something
};

Is it possible to write such a constructor and how is it possible? What is this statement

{{1, 2}, {3, 4}} actually doing?

I always just find, that you can initialize data in this way, but never what it is doing precisely.

like image 430
Markus Avatar asked May 23 '18 13:05

Markus


People also ask

What is use of constructor in C++?

C++ Constructors. Constructors are methods that are automatically executed every time you create an object. The purpose of a constructor is to construct an object and assign values to the object's members. A constructor takes the same name as the class to which it belongs, and does not return any values.

What is the role of a constructor in classes?

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

What is constructor in C++ and its types with examples?

Constructors in C++ are the member functions that get invoked when an object of a class is created. There are mainly 3 types of constructors in C++, Default, Parameterized and Copy constructors.

Does a C++ class need a constructor?

A class doesn't need a constructor. A default constructor is not needed if the object doesn't need initialization.


1 Answers

It is called list initialization and you need a std::initilizer_list constructor, that to be achieved in your my_class.

See (Live Demo)

#include <iostream>
#include <vector>
#include <initializer_list> // std::initializer_list

class my_class
{
    std::vector<int> A;
public:
    // std::initilizer_list constructor 
    my_class(const std::initializer_list<int> v) : A(v) {}    

    friend std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */;
};

std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */
{
    for(const int it: obj.A) out << it << " ";
    return out;
}

int main()
{
    my_class obj = {1,2,3,4};  // now possible
    std::cout << obj << std::endl;
    return 0;
}
like image 57
JeJo Avatar answered Sep 23 '22 22:09

JeJo