Understanding C++/Objects
Objects
[edit | edit source]An object is an abstract idea or thing with characteristics and behaviors that can be manipulated. Objects also have names that people call them by. People use the name, characteristics, and behaviors of an object to define and to differentiate between different types of objects. An object type must be defined or declared before an object of that type can be created and manipulated. In the same way as builders cannot begin to build a school until after they have had a chance to read and understand the school's blueprint.
Basic object types
[edit | edit source]C++ defines 8 basic object types. char
, short
, int
, long
, long long
, double
, long double
, and bool
.
Standard object types
[edit | edit source]C++ defines additional object types in its standard library. Examples include string
and vector
.
New objects
[edit | edit source]New objects are declared using the class
or struct
keyword followed by a name for the object, a body, and a semicolon (;
). The body consists of a block ({}
) of instructions that define the characteristics and behaviors of the object that can be manipulated. You can also define and manipulate other objects inside the body too.
A silly example:
class example
{
int v;
int f();
};
Here the class example
contain two members -- one member variable, called v, and one member function, called f.
Access specifiers
[edit | edit source]All members of an object are either public, protected, or private. This determines where members can be used.
Public
[edit | edit source]Public members can be called and used anywhere. Other objects and functions can call and use public members.
Protected
[edit | edit source]Protected members can only be called and used by the object and through objects that are in the inheritance tree. A object must inherit from an object in order to call and use its protected members. This may seem like a silly thing to do, but sometimes you need to share members and allow those members to behave differently in inherited objects without letting just anyone affect the behavior.
Private
[edit | edit source]Private members can only be called and used by the object itself. Other objects that inherit from the object cannot call or use private members.
Defining member functions outside the class definition
[edit | edit source]Defining the function in the example class is just like defining regular functions, except for one thing. In order to define a member function of a class you must prepend the class name and two colons to the name like so:
int example::f()
{
...
}
The defines the function in the class example
.