0

I know there had been a discussion similar to this in the past but answers appear to be outdated in my opinion. Most say that the differences are the following:

  1. Scope - since on the old questions ask with examples of these objects declared inside the method instead of as a member of the class.

  2. Safety from memory leak - old questions use raw pointers rather than smart pointers

Given my example below, class Dog is a member of class Animal. And is using smart pointers. So the scope and memory leak are now out of the picture.

So that said.. What are the benefits of declaring a class with a pointer rather than a normal object? As basic as my example goes - without considering polymorphism, etc.

Given these examples:

//Declare as normal object class Dog { public: void bark() { std::cout << "bark!" << std::endl; } void walk() { std::cout << "walk!" << std::endl; } }; class Animal { public: Dog dog; }; int main() { auto animal = std::make_unique<Animal>(); animal->dog.bark(); animal->dog.walk(); } 

And..

//Declare as pointer to class class Dog { public: void bark() { std::cout << "bark!" << std::endl; } void walk() { std::cout << "walk!" << std::endl; } }; class Animal { public: Animal() { dog = std::make_unique<Dog>(); } std::unique_ptr<Dog> dog; }; int main() { auto animal = std::make_unique<Animal>(); animal->dog->bark(); animal->dog->walk(); } 
7
  • 5
    It really depends on how your classes are meant to be used. Will they be extended (other methods/logic/members)? As your code stands, there is no point in declaring a pointer there. Commented Jul 23, 2019 at 10:29
  • 1
    If Dog is never derived from then all is fine, but if there are Bulldog and Poodle derived from Dog and both can be assigned to Animal::dog then you have to have a pointer. Commented Jul 23, 2019 at 10:30
  • 1
    With your current example there is only a performance overhead in using a pointer. Commented Jul 23, 2019 at 10:34
  • 4
    Your example is not helpful in exploring benefits or otherwise of pointers, The main benefit of using a Dog * or a std::unique_ptr<Dog> is the ability to use polymorphism IF Dog is a polymorphic base (which it isn't in your example). It is also possible to dynamically create an array of Dog with the size determined at run time (but that array cannot contain instances of classes derived from Dog). In your case (Dog not polymorphic) neither of those benefits can be achieved, and all you have achieved is additional overhead of dynamically creating and destroying objects. Commented Jul 23, 2019 at 10:41
  • 2
    I know it's just an example, but it's a strange model to say "every Animal has a Dog". Commented Jul 23, 2019 at 11:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.