What are the different way of creating object in c++ ?

Questions by vikas kushwah   answers by vikas kushwah

Showing Answers 1 - 0 of 0 Answers

Sainath Rao

  • Dec 6th, 2011
 

Different ways of creating an oject is

shape a = new shape();

a is the object creation of one typefor the shape class with new operator.

shape a;

This is another type of creation of object fot the class.

neeraj

  • Jan 3rd, 2012
 

You are not creating an object you are giving reference.

  Was this answer useful?  Yes

Isaac

  • Feb 21st, 2012
 

1. Create on stack. i.e. ClassA varA;
2. Create on heap. i.e. ClassA *ptrA = new ClassA;

  Was this answer useful?  Yes

NikunjSingh

  • Feb 22nd, 2012
 

1. using normal object creation: Shape obj;
2. copy ctor: Shape obj2=obj;// or Shape obj3(obj);
3. using new operator;

Code
  1. #include <iostream>

  2.  

  3. using namespace std;

  4.  

  5. class Shape{

  6. public:

  7.         Shape(){cout<<"Shape..."<<endl;}

  8.         Shape(const Shape& obj)

  9.         {

  10.                 cout<<"Copy called"<<endl;

  11.         }

  12.         void* operator new(size_t size)

  13.         {

  14.                 cout<<"new...."<<endl;

  15.                 void* storage=malloc(size);

  16.                 if(NULL == storage) {

  17.                         throw "allocation fail : no free memory";

  18.                 }

  19.                 return storage;

  20.         }

  21.  

  22.         void operator delete (void*){

  23.  

  24.         }

  25. };

  26.  

  27. int main()

  28. {

  29.         Shape obj;

  30.         Shape obj2=obj;

  31.         Shape obj3(obj);

  32.         Shape* ptrShape=new Shape();

  33.         Shape* ptrShapeOver= new Shape();

  34.         return 0;

  35. }

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Answer Question

Click here to Login / Register your free account


 
Send   Reset

 

Related Answered Questions

 

Related Open Questions