Reputation: 21514
Consider this trivial class:
#include <string>
class A
{
public:
A( int i, const std::string& str ) : i(i), str(str)
{
}
inline int getValue() const { return i; }
inline std::string getName() const { return str; }
private:
int i;
std::string str;
};
int main()
{
A a(3,"dkd");
//...
return 0;
}
It's "a pain" to have to maintain the constructor when new attributes are added to the class. OK, not that painful, but when the constructor is so obvious (it gets the parameters of the same type than attributes and in the same order), it would be nice not to have to declare any, and have a default one provided that would simply work!
I was thinking of something like:
#include <string>
class A
{
public:
inline int getValue() const { return i; }
inline std::string getName() const { return str; }
private:
int i;
std::string str;
};
int main()
{
A a{ 3, "ff" };
///...
return 0;
}
Is this doable in C++?
Upvotes: 0
Views: 117
Reputation: 7111
Unfortunately not for your case. Something exists which allows you to do this, and it's called aggregate initialisation. It can't be used in your example, because it can only be used on classes which
virtual
functionsFrom the link itself:
Aggregate initialization is a form of list-initialization, which initializes aggregates
An aggregate is one of the following types:
* array type
* class type (typically, struct or union), that has
no private or protected non-static data members
no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
no virtual, private, or protected (since C++17) base classes
no virtual member functions
no default member initializers
If your class had public
members instead, you would be able to have the following:
class A
{
public:
int i;
std::string str;
};
int main()
{
A a{ 3, "ff" };
}
If you then extend your class by adding a new member to it, you don't need to update old code. Members not included in the initialiser list are default initialised:
If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized.
class A
{
public:
int i;
std::string str;
double d;
};
int main()
{
A a{ 3, "ff" }; // your old code still works, a.d becomes 0.0
A b{ 3, "ff", 1.0 };
A c{}; // 0, "", 0.0
}
Upvotes: 4
Reputation: 20936
Read about http://en.cppreference.com/w/cpp/language/aggregate_initialization, your code will not be compiled bacause members of your class are privated.
If members of your class are public, your code will work.
Upvotes: 1