Class¶
C++ classes are a tool for creating new types that can be used conveniently as builtin types The Fundamental idea in defining a new type is to separate the details of the implementation from the properties essential to the correc use of it
Brief Summary of classes¶
- A class is user-defined type
- A class consists of a set of members. The most common kinds of members are data members and member functions.
- Member functions can define the meaning of initialization, copy, move, and cleanup
- Members are accessed using
.
(dot) for objects and->
(arrow) for pointers. - Operators, such as,
+
,!
, and[]
, can be defined for a class - A class is a namespace containing its members
- The
public
members provide the class's interface and theprivate
members provide implementation details - A
struct
is aclass
where members are by defaultpublic
Class Basics¶
class example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1. Member functions¶
Functions declared within a class definition are called member functions
2. Default copying¶
a class object can be initialized with a copy of an obejct of its class
1 2 |
|
3. Access Control¶
class is consist of two parts
private
part: can be used only by member functions,public
part : interface to objects of class
4. class
and struct
¶
a
struct
is a class in which members are by defaultpublic
struct S{};
is simply short hand forclass S{public: };
5. Constructors¶
a
constructor
is recognized by having the same name as the class it self. programmers can declare a function with the explicit purpose of initializing objects.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
I recommend the {}
notation over the () notation for initializing, because it is explicit about what is being done
we could use default values directly as default arguments
1 2 3 4 5 |
|