Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C2440: 'initializing' : cannot convert from 'initializer-list'

#include<iostream>
using namespace std;
struct TDate
{
    int day, month, year;
    void Readfromkb()
    {
        cout << "\n ENTER DAY MONTH YEAR\n";
        cin >> day >> month >> year;
    }
    void print()
    {
        cout << day << month << year;
    }
    private:
        int ID;
        bool valid;

};
int main()
{
    TDate t1, t2,t3={ 1, 2, 3 };
    t1.Readfromkb();
    t1.print();
    cin.ignore();
    cin.get();
    return 0;

}

why i'm getting Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'TDate' and 2 IntelliSense: too many initializer values. When I remove bool valid and int ID the programs works.Why is it so?

like image 481
Fatima Rashid Avatar asked Oct 25 '15 08:10

Fatima Rashid


2 Answers

You are getting the error because you are trying to initialize a TDate from an aggregate initialization list. This cannot be done when the type has private members (such as, in your case, ID and valid).

You can work around this by providing a constructor for your struct from three ints and using TDate t1, t2, t3(1, 2, 3).

like image 150
Oblomov Avatar answered Oct 21 '22 22:10

Oblomov


To do t3={ 1, 2, 3 }; you have to make constructor of TDate with takes three arguments, like this:

TDate(int i, int i1, int i2);

and implement it using:

TDate::TDate(int i, int i1, int i2) {

}

if you dont want to create constructor, then create object like this:

TDate t1 = TDate();
like image 43
vishal Avatar answered Oct 21 '22 23:10

vishal