A quick check...

T

Tomás

class Base
{
public:

int* const p;

Base(int* const x) : p(x) {}
};

class Derived : public Base
{
public:

int monkey[8];

Derived() : Base(monkey) {}
};

int main()
{
Derived k;
}


Is this okay? Can I be certain that "monkey" will have been created before
the constructor of the Base class is called?

-Tomás
 
P

Phlip

Tomas said:
class Base
{
public:

int* const p;

Base(int* const x) : p(x) {}
};

class Derived : public Base
{
public:

int monkey[8];

Derived() : Base(monkey) {}
};
Is this okay? Can I be certain that "monkey" will have been created before
the constructor of the Base class is called?

Construction happens from top to bottom. Base will fully construct, with the
address where monkey will be, before monkey constructs.

However, monkey already has storage, so it can point to it.

New question; how defined is this?

Base(int* x) : p(x)
{
*p;
p[3] = 42;
int whatever = p[4];
}

All those lines deference valid storage containing an unconstructed int.
Ints have trivial constructors, but I thought I heard that all three of
those lines generate technically undefined behavior.

They will probably "work". Don't do any of this in professional code.
 
V

Victor Bazarov

Tomás said:
class Base
{
public:

int* const p;

Base(int* const x) : p(x) {}
};

class Derived : public Base
{
public:

int monkey[8];

Derived() : Base(monkey) {}
};

int main()
{
Derived k;
}


Is this okay? Can I be certain that "monkey" will have been created before
the constructor of the Base class is called?

It is OK. The storage for 'Derived' is allocated before the constructor
is invoked. So, 'monkey' array is allocated and the address of it is well
known. Passing that address to the base class for storing is OK.

This practice, however, is shady because if I attempt to access 'x' for
whatever reason in 'Base's constructor, then the behaviour is undefined.

V
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top