0

I have this code and the exercise is to find out which error will occur if I build an Instance of my Class and delete it afterwards. I can't find the fault in the definition of this class so maybe you can help me. Here's the code:

class BadClass{ public: BadClass(){ p = new double; } ~BadClass () {} double getValue() {return *p;} void setValue(double v) {*p = v;} private: double* p; }; 
1

1 Answer 1

2

You call new double in the constructor without a corresponding delete p call in the destructor.

This will result in a memory leak.

Sign up to request clarification or add additional context in comments.

3 Comments

Alright thank you @APerson I already thought about this so the standard destructor does not delete dynamic allocated memory?
@Franklinprogs no, you must manage the memory ownership manually in C++. You can however use std::shared_ptr<T> and std::unique_ptr<T> helper classes
@Erbureth: or even double in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.