Advantage to pointers?

closed account (D1AqM4Gy)
So I have just started C++ and I'm at pointers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

class Start
{
    public:
    void Happy()
    {
        std::cout << "I'm Happy!" << std::endl;
    };

};

int main()
{
    // Simple
    Start s;
    s.Happy();

    // Pointer
    Start *one = new Start();
    one->Happy();
};


In this code I am wondering if there is a advantage to using pointers instead or the simple way ( ie. Simple being s.Happy();, and pointers being one->Happy(); )

If anyone can clear this up for me I would very much appreciate it. Thanks!
In this case pointers aren't necessary. Plus, having new'd an object into existence, you need to delete it somewhere.

The source of confusion is that in C++, class can mean a number of things. In Object Oriented Programming, an object is defined using the keyword class. An object has a number of overrideable methods and you must use them thru pointers.

Consider this code fragment:
1
2
3
4
    if (Shape* shape = UI::CreateShape())
    {
        double area = shape->getArea();
        double circumfrence = shape->getCircumfrence();
This gets a shape and gets the shape to calculate its area and circumfrence, then goes of and uses them. The things to note are:
1. You don't need to know exactly what shape it is--polymorphism.
2. You can ask the shape to do things that are shape specific, and expect the right thing to be done.

Another use of class is just to encapsulate something, these aren't objects, they're abstract data types. When dealing with abstract data types, you tend to work with the concrete type and know what you're dealing with and you don't need to access them thru pointers. For example:
 
   std::vector<Shape*> shapes = LoadShapes();
This example uses an abstract data type, std::vector, and an object, shape.

Class is also used to define object interfaces; pointers again.
Topic archived. No new replies allowed.