vikas yadav
vikas yadav

Reputation: 21

initialising vector of pointers for a user defined class

I tried to initialize a vector of pointers but got some error, both code and the errors are below

class tr
{
public:
    int n = 26;
    vector<tr* >  a(n  ,NULL);

};

the error I got is :

try_class.cpp:7:25: error: ‘n’ is not a type
        vector<tr* >  a(n  ,NULL);
                        ^
try_class.cpp:7:29: error: expected identifier before ‘__null’
        vector<tr* >  a(n  ,NULL);
                            ^~~~
try_class.cpp:7:29: error: expected ‘,’ or ‘...’ before ‘__null’

I could not figure out what is wrong with my code

Upvotes: 1

Views: 225

Answers (1)

Jarod42
Jarod42

Reputation: 218323

Parents are not allowed for member initialization (to avoid most vexing parse issue).

You might do instead:

class tr
{
public:
    int n = 26;
    std::vector<tr*>  a{std::size_t(n), nullptr};
};

or

class tr
{
public:
    int n = 26;
    std::vector<tr*> a = std::vector<tr*>(n, nullptr);
};

Upvotes: 2

Related Questions