Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ran into this at work "operator ClassName *". What does this mean?

Tags:

c++

The class with this code is a reference class for a pointer of ClassName, i.e.:

class ClassName;

class ClassRef
{
    ClassName* m_class;
    ...
    operator ClassName *() const { return m_class; }
...

I am assuming this is used for pointer validity checks, such as:

ClassRef ref(new ClassName())
if (ref) { bla bla bla }

Am I correct in my thinking?

like image 337
NindzAI Avatar asked Nov 27 '12 20:11

NindzAI


People also ask

What does & mean with classname?

The ampersand is part of the type in the declaration and signifies that the type is a reference. Reference is a form of indirection, similar to a pointer.

When an operator is given user defined meaning then it is called?

Introduction to Operator Overloading It's a type of polymorphism in which an operator is overloaded to give it the user-defined meaning. C++ allows us to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading, respectively.

Which is faster i ++ or i 1?

As i++ does automatic typecasting and uses a compiler instruction which internally uses iadd instruction, i=i+1 is faster than i++.


1 Answers

This is an overload of the conversion operator. Whenever a ClassRef object needs to be converted to a ClassName pointer type, this operator is called.

So;

ClassRef r;
ClassName * p = r;

will make use of this overload.

like image 110
enobayram Avatar answered Oct 26 '22 23:10

enobayram