Q:- create a class in which you will declare a pointer to int . This variable will be defined n allocated memory in the constructor. Create a destructor of the class where this memory will be deallocated.

Using this class do the following:

1) In the main function create an instance of this class

2) Create another function outside main function( lets call it foo) and pass it by value the object created in the main function.

3) Once foo is finished, try to access the int* defined within class in the main and see what happens ?

4) Do you get any problem at the end of the program ? If yes, why ?

5) Try to correct this problem using copy constructor

Program:

//#include <iostream>

using namespace std;

class salu
{

public:
       int* ptr;

///////////////////////// constructor//////////////////////////

       salu() 

        {
            ptr= new int;

        }

//////////////////////////destructor///////////////////////////

        ~salu()  
        {
            delete ptr;

        }

///////////////////////copy constructor/////////////////////////

        salu(const salu &d)
        {

         int* ptr;
         ptr = new int;
         ptr=d.ptr;


        }

};

//////////////////////////Function Foo//////////////////////////

void foo(salu x)
{




}

////////////////////// Start of main/////////////////////////////

void main()
{
    salu a;
    foo(a);
    cout<<a.ptr<<endl;

}

1. Use code tag properly:
[code=cplusplus] your code

[/code]
2. int main() , never write void main() !
3. What's your test plan? What did you want to achieve with this code?
4. What's your problem now? If you have a run time error, what's this error? No explanation...

Well, that's the first (but not the last) error: in the copy constructor you declare local ptr variable. It's not the ptr class member! You save a pointer to an allocated memory to this variable then overwrite it immediately. The ptr member of "constructed" object is not initialized. In other words, your copy "constructor" has null effect and parameter x in the function foo is not constructed properly. Therefore its destructor failed...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.