Wednesday, 14 September 2016

c++ - Benefit of declaring class as pointer?

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->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();
}
std::unique_ptr dog;
};

int main()
{
auto animal = std::make_unique();
animal->dog->bark();
animal->dog->walk();

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...