Single member pointers in OOP

56 views Asked by At

Im a student and I faced a problem to understand the concept of single member pointers in object-orianted-programming (OOP) and I searched a lot on Google but did not got the idea!

Can you help me understanding it in details please?

1

There are 1 answers

2
Alex On

So after further clarification from the comments, you seem to be wondering about pointer members in a class, like this:

class Foo
{
public:
  int* a;
};

Now pointers in classes are basically the same as normal variables, but since you are dealing with memory here, you will be 3 additional things (Rule of Three):

  1. Destructor
  2. Copy Constructor
  3. overloaded operator=

I won't go too much into detail here, but it should look something like this:

class Foo
{
private:
  int a*;

public:
  ~Foo() // destructor
  {
    delete a;
  }

  Foo(const Foo& cpy) // copy constructor
    : a(cpy.a) {}

  Foo& operator=(const Foo& cpy) // assignment
  {
    a = copy.a;
  }
};

Please learn about those three, called the Rule of Three, before you move on with pointers as attributes in a class.

And whenever you find yourself using pointers inside a class, you need to implement the Rule of Three.

Hope this helps :)