Boby
Boby

Reputation: 125

Inheritance and array of types

I have a probably very simple question in C++. Let's say I have class defined as:

class PS { private:

int value;

int m;

public:

PS();
PS(int value, int m);
PS(int m);

};

Now I want to define an array with elements of this type. For example,

PS t[3];

However, I want all of the elements in this array to have m=2. How would I do that? I am assuming I have to use inheritance some how, right? So for example I don't want to do something like this:

>PS t[3]; 
>t[0].PS(2);
>t[1].PS(2);
>t[2].PS(2);

I want to do it one show for all elements of t.

Upvotes: 1

Views: 75

Answers (3)

scohe001
scohe001

Reputation: 15446

The STL Vector class is preferred to c-arrays. Using one, you could do:

std::vector<PS> t(3, PS(2));

Upvotes: 1

&#201;ole
&#201;ole

Reputation: 11

It is not really safe not to initialize a value but you can use the C++11 feature that allows you to initialize variable directly in your class definition :

class PS { 
private: 
  int value;
  int m = 2;

public:
  PS() {};
};

If you are using an older version of C++ you can consider overloading the default constructor

class PS { 
private: 
  int value;
  int m;

public:
  PS(int _m = 2) : m(_m) {};
};

Upvotes: 1

quantdev
quantdev

Reputation: 23793

Using your constructor, you can simply use brace initialization :

PS t[] = { PS(2) , PS(2), PS(2) };

Or as suggested by @0x499602D2, since PS has a non explicit constructor, simply :

PS t[] = { 2, 2, 2 };

I would also suggest you to use std::array<> instead of C-style arrays.

Upvotes: 1

Related Questions