How member initialization list works?

S

Stanley Rice

Hello all

In the following class definition:

class iStack {
public:
iStack( int capacity )
: _stack( capacity ), _top( 0 ) {}
// ...
private:
vector< int > _stack;
int _top;
};

The date member _stack is initialized in the form _stack(capacity) in the
member initialized list. My question, how it could be? the type of _stact
is vector<int>, but the type of capacity is int.

I wander if the conversion function is called? Then I wrote the following
code:
vector<int> va = 2;
but the compiler complains.

However, If the define another class, say,

class A
{
public:
A(int a) : ia(a) {}

private:
int ia;
};

Then the code
A ca = 2;
pass.

What's the difference ?
 
G

Goran

Hello all

In the following class definition:

class iStack {
    public:
        iStack( int capacity )
            : _stack( capacity ), _top( 0 ) {}
        // ...
    private:
        vector< int > _stack;
        int _top;

};

The date member _stack is initialized in the form _stack(capacity) in the
member initialized list. My question, how it could be? the type of _stact
is vector<int>, but the type of capacity is int.

I wander if the conversion function is called? Then I wrote the following
code:
    vector<int> va = 2;
but the compiler complains.

However, If the define another class, say,

class A
{
public:
    A(int a) : ia(a) {}

private:
    int ia;

};

Then the code
    A ca = 2;
pass.

What's the difference ?

1. keyword "explicit"
2. (unrelated, I think) vector can be created off a size_t (unsigned).
You tried signed.
 
J

Juha Nieminen

Stanley Rice said:
In the following class definition:

class iStack {
public:
iStack( int capacity )
: _stack( capacity ), _top( 0 ) {}
// ...
private:
vector< int > _stack;
int _top;
};

The date member _stack is initialized in the form _stack(capacity) in the
member initialized list. My question, how it could be? the type of _stact
is vector<int>, but the type of capacity is int.

You are calling the std::vector constructor that takes takes a size_type
and a value of the member type (in this case int). The latter has a default
value, which is why you don't have to specify it. The former initializes the
vector with the specified amount of elements, which is what the code above
is doing.

(Ok, technically speaking that constructor takes three parameters, the
third one being an allocator. But that one also has a default value so
you don't have to specify it.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top