Dementor
Dementor

Reputation: 251

Using class pointers vs instance

What I don't understand is what is the difference between using a pointer to a class and generating a new instance of it. It's just for performance? Here I made a class and made m the pointer to the class and n the instance of the class. And another question: can i make a pointer the class and use another constructor? like myClass* p(7); p->afis(); ?

#include <iostream>
using namespace std;

class myClass
{
    int a;
public:
    myClass(void);
    myClass(int);
    void afis();
    ~myClass(void);
};

myClass::myClass(void)
{
    a = 5;
}

myClass::myClass(int nr)
{
    a = nr;
}

void myClass::afis()
{
    cout << a;
}

myClass::~myClass()
{
}

int main()
{
    myClass* m;                                     //<--
    m->afis();

    myClass n(7);                                   //<--
    n.afis();

    cin.get();
}

Upvotes: 8

Views: 14532

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283941

can i make a pointer the class and use another constructor

Making a pointer doesn't call a constructor. The pointer is uninitialized until you set it to the address of some object (maybe a brand new object created with new).

myClass* m;                                     //<--
m->afis();

This is undefined behavior, you have a wild pointer because m hasn't been initialized.

Better:

std::unique_ptr<myClass> m(new myClass(constructor, args, here));                                     
m->afis();

Upvotes: 4

Alok Save
Alok Save

Reputation: 206646

myClass* m;   

is just an pointer to the type myClass it does not point to any valid object, dereferecing such a pointer is Undefined Behavior.

An Undefined Behavior means that your program is invalid and it may seem to work or it may crash or it may show any weird behavior, all safe bets are off. So just because your program works does not mean it is safe and it will always work.

To write a valid program you will have to make the pointer point to a valid object.
For example:

myClass obj;
myClass*m = &obj;

In the second case:

 myClass n(7);

It creates an object n of the type myClass by calling the constructor of myClass which takes one argument of the type int.
This is a valid way of creating an object.

Upvotes: 10

Related Questions