Learn C++ - C++ Custom Types
Define your own data types
You can define new data types by defining a class.
A class type can be a combination of base types of other types or variables of other class types.
A class can also have functions that are part of its definition.
You can define a type of Box that contains variables that store the length, width and height to represent the box.
You can then define variables of type Box just as you would define variables of primitive types.
Each Box object will contain its own length, width and height dimensions, and you can create and manipulate as many Box objects as you want in your program.
Classes are user-defined data types.
Variables and functions defined in a class are members of the class.
Variables are data members and functions are function members.
The function members of a class are sometimes called methods.
A variable of type stores the object. Objects are sometimes called instances of classes.
Defining an instance of a class is called instantiating.
object oriented
Object-oriented programming incorporates some other important ideas (the famous encapsulation and data hiding, inheritance and polymorphism).
Inheritance is the ability to define one type in terms of another.
Polymorphism is the ability to take different forms at different times.
Polymorphism in C++ always involves calling a function member of an object using a pointer or reference.
define class
A class is a user-defined type.
Types are defined using the class keyword. The basic organization of a class definition is as follows:
class ClassName
{
// Code that defines the members of the class...
};
The name of this type is ClassName.
It is a common convention to use the uppercase names of user-defined classes to distinguish type and variable names.
Members of a class are specified between curly braces.
The definition of function members can be inside or outside the class definition.
class Box {
private:
double length {1.0};
double width {1.0};
double height {1.0};
public:
// Function to calculate the volume of a box
double volume() {
return length*width*height;
}
};
length, width and height are the data members of the Box class, all of which are of type double.
Each Box object has its own set of data members.
This is pretty obvious - all objects are the same if they don't have data members of their own.
You can create a variable of type Box like this:
Box myBox; // A Box object with all dimensions 1
The myBox variable refers to the Box object with default data member values. You can call the volume() member of this object to calculate the volume:
std::cout << "Volume of myBox is" << myBox.volume() << std::endl; // Volume is 1.0
You can designate data members as public, in which case you can set them explicitly from outside the class like this: