Developer Resources’s Weblog

June 6, 2008

Accelerated c++ Chapter 11 – Defining abstract data types

Filed under: Accelerated C++, Book Reviews, c++ — Tags: , , , — developerresources @ 3:37 am

The Page continues the discussion of Accelerated C++: Practical Programming by Example (C++ In-Depth Series).

An abstract data type defines a public interface for others to use while hiding the private implementation. In c++ an abstract data type will typically have a signature like this:


class MyAbstractClass
public:
// interface
private:
// implementation

This chapter introduces the explicit keyword. In c++ a constructor is also an implicit type conversion operator. For example consider the following

class MyInt{
public:
MyInt(int i);
};

// then you create new
MyInt i = 5;

The assignment MyInt i =5 will actually turn into compiler generated code that looks like this

MyInt temp(5);
i=temp;

By using the “explicit” keyword you can instruct the compiler not to allow this. In this contrived example you shouldn’t, but when you start to deal with very complex times you may worry about performance of these temporary objects.

Copy Constructor
In c++ you have the ability to define you how you class is copied. That is what happens when someone execute the following on your defined class:

MyClass mc1;
MyClass mc2 = mc1;

For a simple object a straight member-wise copy may be sufficient (which is the default behavior) but if you have a deep data structure then you should provide a copy constructor.

A copy constructor takes the following form:

class MyClass {
public:
MyClass(const Myclass& c); // copy constructor
}

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.