Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does class pointer* means?

Tags:

c++

I got this syntax I don't really understand:

class USphereComponent* ProxSphere;

I think this means create a class, but is this class a pointer?

But the result is just creating an object called ProxSphere from an existing class USphereComponent.

What does this syntax actually mean, and what is its usage?

like image 981
JT Woodson Avatar asked Dec 05 '22 19:12

JT Woodson


2 Answers

class Someotherclass; // That has not been defined yet

class HelloWorld
{
    Someotherclass* my_pointer;
};

Or an alternative:

class HelloWorld
{
    class Someotherclass* my_pointer;
};

The first one is obviously the correct one if you have multiple pointers (or references) to such class that has not been defined yet.

Is the second better? (I don't know) if you only need to do it once, otherwise doing

class HelloWorld
{
    class Someotherclass* my_pointer;
    class Someotherclass* my_pointer2;
    class Someotherclass* my_pointer3;

    void func(class Someotherclass* my_pointer, class Someotherclass& my_ref);
};

may not be the best.

like image 171
Jts Avatar answered Jan 09 '23 06:01

Jts


Jts's answer is correct. I'd like to add a use case for it:

This is mostly used when you have a circular class dependency.

Like:

class A { B* binst; };
class B { A* ainst; };

That wouldn't compile since B isn't previously known.

Therefore you would first declare class B.

class B;
class A { B* binst; };
class B { A* ainst; };

Or as mentioned, you can use syntactic sugar:

class A { class B* binst; };
class B { A* ainst; };

Such a dependency might be a code smell. It also might be ok or even necessary. If you have it, you should carefully think if you can't do it in some other yet convenient way.

like image 21
Tomáš Růžička Avatar answered Jan 09 '23 08:01

Tomáš Růžička