POO

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
david_stelian
Junior
Junior
Posts: 20
Joined: 13 Sep 2014, 22:35
Judet: Dolj

POO

Post by david_stelian » 26 Apr 2015, 12:45

Imi poate spune cineva de ce cand afisez pe r cu obiectul second imi afiseaza "garbage" ?

Code: Select all

#include <iostream>
using namespace std;

class numar
{
private:
    int *p;
    int *r;
public:
    numar(int);
    numar(const numar&);
    void display();
    ~numar();
};

int main ()
{
    numar first(100);
    first.display();
    numar second(first);
    first.display();
    second.display();
    return 0;
}

numar::numar(int x)
{
    p = new int;
    *p = x;
}

numar::numar(const numar &ob)
{
    r = new int(*ob.p);
}

void numar::display()
{
    cout << "\n Value of p is " << *p << endl;
}

numar::~numar()
{
    delete p;
}



User avatar
Silviu Ardelean
Senior
Senior
Posts: 1175
Joined: 12 Jul 2007, 09:22
Judet: Timiş
Location: Timisoara
Contact:

Re: POO

Post by Silviu Ardelean » 26 Apr 2015, 20:13

Atributul pointer p in cazul obiectului second este garbage pentru ca acel pointer nu-l initializeaza nimeni.

Atentie: folosind copy-constructorul, pentru ca iti lipsesc lucruri in ambi constructori, cat si in destructor, inevitabil ajungi sa corupi heap-ul pe destructor (double free).
Iti recomand sa le completezi cu ceva de genul:

Code: Select all

numar::numar(int x)
{
    p = new int;
    *p = x;
    r = new int;
    *r = 0;
}

numar::numar(const numar &ob)
{
    r = ob.r;
    p = ob.p;
}

numar::~numar()
{
  if (p != 0)
    delete p;
  
  p = 0;
  
  if (r != 0)
    delete r;
 
  r = 0;
}

david_stelian
Junior
Junior
Posts: 20
Joined: 13 Sep 2014, 22:35
Judet: Dolj

Re: POO

Post by david_stelian » 26 Apr 2015, 20:53

Multumesc pentru amabilitate!

Post Reply