Saturday, June 14, 2008

Chapter 9 - Defining new types

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


There are two types in C++ built-in types and class types. Built-in types are part of the core language (int, double, char, etc) whereas class types are typically built on top of the built-in types (vector, string, user-defined classes, etc).

Chapter 9 of Accelerated C++ revisits example from previous chapters and implements them as Classes. For those of you who don't know a simple class in c++ can be declared as follows:


class MyClass {
std::string my_field;
public:
std::string getMyField() const { return my_field;}
}


The above code declares a class ( all methods default to private access ) with one member field, and one assesor function.

Member Functions
As you see above our classes not only contain data but also member functions. When should you use a member function? The general rule is when the function changes the state of the object.

Accessor functions
Accessor functions are names given to member functions that serve to expose hidden fields of the object.

Constructors
Constructors hold code that is executed upon object construction. More formally, "Constructors are special member functions that define how objects are initialized."

A constructor can take no arguments, known as the default constructor or it can take variables that you use for initialization.

user-defined types can be defined as either structs or classes. Structs default to always public access, where as classes start with private access.

Protection labels control access to members, both fields and function, of a class or struct. So you can start with a struct and declare parts private, or you can start with a class and decalare parts public.

Constructor initializer list is a comma separated list of member-name(value) pairs that indicate how to initialize the object.

No comments: