Course list http://www.c-jump.com/bcc/
In C, the structures are introduced by the struct keyword.
The struct aggeregates data members into a single object.
The struct can be used as a user-defined data type:
#include <iostream>
struct Rectangle {
int width; // member variable
int height; // member variable
};
int main()
{
Rectangle rect { 20, 10 };
std::cout << "rectangle width: " << rect.width << '\n';
std::cout << "rectangle height: " << rect.height << '\n';
return 0;
}
In this sample, the rect is an object. This object is the result of instantiation of the struct Rectangle.
In C++, the struct may also contain functions as members. For example,
struct Rectangle {
int width; // member variable
int height; // member variable
// C++
void set_dimensions( int width_ , int height_ )
{
width = width_;
height = height_;
}
int area() const
{
return ( width * height );
}
};
Similar to variables, the struct must be defiend before it can be used.
Notice that member function area( ) is declared const. The const modifier tells the compiler that the function does not modify the object's state, only reading its data.
With set_dimensions() and area() member functions added to
the Rectangle struct, the main() function can be re-written as follows:
int main()
{
Rectangle rect { 20, 10 };
std::cout << "rectangle width: " << rect.width << '\n';
std::cout << "rectangle height: " << rect.height << '\n';
std::cout << "rectangle area: " << rect.area() << '\n';
rect.set_dimensions( 44, 33 );
std::cout << "updated rectangle width: " << rect.width << '\n';
std::cout << "updated rectangle height: " << rect.height << '\n';
std::cout << "updated rectangle area: " << rect.area() << '\n';
return 0;
}
In our example we used initializer list to provide the initial values to the width and height of the rect object:
Rectangle rect { 20, 10 };
However, we may want to use other forms of the rectangle initialization:
Rectangle rect; // use default values
Rectangle rect2( 100 ); // make it a square where width = height = 100
If we try
int main()
{
Rectangle rect;
std::cout << "rectangle width: " << rect.width << '\n';
std::cout << "rectangle height: " << rect.height << '\n';
return 0;
}
the output of width and height values yields undetermined result.
An attempt to create rect2 won't even compile:
Rectangle rect2( 100 ); // *** compiler error: no matching function for call
Constructors provide support for multiple ways of object creation and initialization.
Constructor is a special member function.
Every declaration of an object results in the calling of a constructor.
How are constructors defined?
struct Rectangle {
int width; // member variable
int height; // member variable
// C++ constructors
Rectangle()
{
width = 1;
height = 1;
}
Rectangle( int width_ )
{
width = width_;
height = width_ ;
}
Rectangle( int width_ , int height_ )
{
width = width_;
height = height_;
}
// ...
};