C++ Tutorial - Function members in classes:
Functions declared inside a class can be any of the following four types. This C++ Tutorial explains each one of them as below.Ordinary member functions :
These are ordinary functions defined with a return type and parameters. The return type can also be void. The special trait about member functions is they can access the private/protected data members of their class and manipulate them. No external functions can access the private/protected data members of a class. The sample below this C++ Tutorial uses an ordinary member function Add(), returning an integer valueConstructors in C++ are special member functions of a class. They have the same name as the Class Name. There can be any number of overloaded constructors inside a class, provided they have a different set of parameters. There are someimportant qualities for a constructor to be noted.Destructors in C++ also have the same name, except for the fact that they are preceded by a '~' operator. The destructors are called when the object of a class goes out of scope. It is not necessary to declare a constructor or a destructor inside a class. If not declared, the compiler will automatically create a default one for each. If the constructor/destructor is declared as private, then the class cannot be instantiated. Check below for the sample class of the C++ tutorial for an example of destructor..Constructors:
- Constructors have the same name as the class.
- Constructors do not return any values
- Constructors are invoked first when a class is initialized. Any initializations for the class members, memory allocations are done at the constructor.
Destructors:
C++ Tutorial - Access Level:
The classes in C++ have 3 important access levels. They are Private, Public and Protected. The explanations are as follows.Private:
The members are accessible only by the member functions or friend functions.Protected:
These members are accessible by the member functions of the class and the classes which are derived from this class.Public:
Accessible by any external member. Look at the sample class below.C++ Tutorial - Example of a class:
class Example_class //Sample Class for the C++ Tutorial
{
private:
int x; //Data member
int y; // Data member
public:
Example_Class() //Constructor for the C++ tutorial
{
x = 0;
y = 0;
}
~Example_Class() //destructor for the C++ Tutorial
{ }
int Add()
{
return x+y;
}
};
{
private:
int x; //Data member
int y; // Data member
public:
Example_Class() //Constructor for the C++ tutorial
{
x = 0;
y = 0;
}
~Example_Class() //destructor for the C++ Tutorial
{ }
int Add()
{
return x+y;
}
};
No comments:
Post a Comment