Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: non-aggregate type 'Circle' cannot be initialized with an initializer list

Tags:

c++

I'm in need of help with an assignment for my C++ class. My problem is trying to compile a program I got from my professor. Every time I try to compile the code I get the following error

"error: non-aggregate type 'Circle' cannot be initialized with an initializer list

Circle list[] ={  { 93, "yellow" }, 

same error follows for the second circle in the array. Can someone tell me what I need to do to get this code to compile?

#include <iostream>
#include "Circle.h"
#include <string>
using namespace std;

int main()
{
 Circle list[] ={  { 93, "yellow" },
                   { 27, "red"    }
                };

 Circle *p;
 p = list;

 cout<<(*p).getRadius()<<endl;
 cout<<(*p).getColor()<<endl;
 cout<<p->getRadius()<<endl;
 cout<<p->getColor()<<endl;

 p++;

 cout<<(*p).getRadius()<<endl;
 cout<<(*p).getColor()<<endl;
 cout<<p->getRadius()<<endl;
 cout<<p->getColor()<<endl;

 return 0;
}//end main
like image 700
itsmluca Avatar asked Oct 20 '25 02:10

itsmluca


1 Answers

What version of C++ are you using? Before C++11, any class with at least one constructor could not be constructed using an aggregate list:

struct A
{
    std::string s;
    int n;
};
struct B
{
    std::string s;
    int n;

   // default constructor
    B() : s(), n() {}
};

int main()
{
    A a = { "Hi", 3 }; // A is an aggregate class: no constructors were provided for A
    B b; // Fine, this will use the default constructor provided.
    A aa; // fine, this will default construct since the compiler will make a default constructor for any class you don't provide one for.
    B bb = { "Hello", 4 }; // this won't work. B is no longer an aggregate class because a constructor was provided.
    return 0;
}

I daresay Circle has a constructor defined, and cannot be constructor with an aggregate initialisation list pre C++11. You could try:

Circle list[] = { Circle(93, "Yellow"), Circle(16, "Red") };
like image 89
Tas Avatar answered Oct 21 '25 17:10

Tas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!