Create Object inside a Class in C++ -


here code

class test {   tbutton *asd; public :   test(){       asd->text = "test";   } }; 

the problem won't work. because object hasn't been constructed using new operator. when tried using new operator, return error , doesnt compiled. anyhelp appreciated.

i using c++ builder.

you need this:

  test() : asd(new tbutton(...)) {       asd->text = "test";   } 

otherwise you're using uninitialized pointer. note syntax i've used there called "initialization list" , many times it's best way write constructor.

of course you'll need add matching destructor:

  ~test() {     delete asd;   } 

but "rule of three" (or five) tell add more methods, instead, avoid using raw pointer, , use "smart pointer":

class test {   std::unique_ptr<tbutton> asd; public :   test() : asd(new tbutton(...)) {       asd->text = "test";   } }; 

now don't need user-defined destructor.


Comments