HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Basic C++ object class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
objectclassbasic

Problem

I have implemented a basic object class in C++, and I want to make sure that I have implemented everything efficiently and safely, as I made a few mistakes while making it, which I corrected, but I could have left a few more mistakes behind:

```
class object
{
private:
class dummy
{
public:
dummy()
{
}
virtual ~dummy()
{
}
virtual const std::type_info &type() = 0;
virtual dummy *duplicate() const = 0;
virtual bool eq(object &) = 0;
};

template class data : public dummy
{
public:
data()
{
}

data(const _Ty &_Value)
: __data(_Value)
{
}

~data()
{
}

const std::type_info &type()
{
return typeid(_Ty);
}

data *duplicate() const
{
return new data(__data);
}

bool eq(object &_Obj)
{
return _Obj.cast() == __data;
}

_Ty __data;
};

dummy *d;
public:
object()
{
}

template object(const _Ty &_Value)
: d(new data(_Value))
{
}

object(const object &_Obj)
: d(_Obj.d->duplicate())
{
}

~object()
{
if (!empty())
{
delete d;
}
}

const std::type_info &type()
{
return (empty() ? typeid(void) : d->type());
}

object &operator=(object &_Rhs)
{
d = _Rhs.d->duplicate();
return *this;
}

object &swap(object &_Rhs)
{
std::swap(*this, _Rhs);
return *this;
}

template object &operator=(const _Ty &_Value)
{
d = new data(_Value);
return *this;
}

template _Ty cast()
{
if (type() == typeid(_Ty))
{
return static_cast *>(d)->__data;
}
throw std::exception("Invalid cast type");
}

bool operator==(object &_Rhs)
{
r

Solution

-
As per common naming convention, the class names should start with a capital letter.

-
It may be more readable to put the template line above the class line:

template 
class data : public dummy
{
}


-
Your bool functions should be const. Any member function that doesn't modify data members should be const. Such functions also include accessors ("getters") and the bool operators (operator==, operator!=, operator).

For instance, with empty():

bool empty() const
{
    // ...
}


and operator==:

bool operator==(object &_Rhs) const
{
    // ...
}


Also, the above parameter should be const& since _Rhs is not being modified.

-
If you're not defining your own constructor and/or destructor, you don't need to make them yourself. The compiler will make them for you.

However, if you're using C++11, you can have an explicitly defaulted constructor and destructor:

data() = default;
~data() = default;

Code Snippets

template < typename _Ty >
class data : public dummy
{
}
bool empty() const
{
    // ...
}
bool operator==(object &_Rhs) const
{
    // ...
}
data() = default;
~data() = default;

Context

StackExchange Code Review Q#42681, answer score: 7

Revisions (0)

No revisions yet.