Reputation: 503
I have one doubt regarding this code that this code is not correct. it can crash at run time.As p pointer is pointing to address of derived class member variable(char array) but before derived class constructor base class constructor gets called so memory initialization and allocation for derived class is not yet done. So when in base class constructor we do strcpy this code might crash.
class Base
{
public:
char *p;
Base(){};
Base(char *a):p(a)
{
sprintf(a,"HELLO");
};
};
class Derived:public Base
{
public:
char arr[10];
Derived():Base(arr)
{
};
};
int main()
{
Derived d = new Derived();
return 0;
}
From This code what i intend to do is to give address of char array to base class where some string needs to be written on address passed. But i am not sure this code will work always. Please clarify.
Upvotes: 0
Views: 923
Reputation: 254431
This is well-defined, but fragile - it can break if you change the type of arr
.
Storage is allocated for the complete object before running any constructor and, since arr
has trivial initialisation, its lifetime begins as soon as storage has been allocated. It's therefore usable in the Base
constructor.
If it were a non-trivial type, like std::string
, then it wouldn't be usable in the Base
constructor, and you'd have undefined behaviour.
Upvotes: 4