0

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;

}

Edited by Reverend Jim: Fixed formatting

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by ArkM
0

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...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.