C++ Notes Bsc csit Second semester chapter 2
Reference on C++ unit2
1.Class And Object :
In C++, an object is an instance of a class. A class is a blueprint or prototype that defines the variables and methods (functions) common to all objects of a certain kind.
For example, you might define a class called "Dog" that includes variables for the dog's breed, age, and weight. The class might also include methods like "bark" and "fetch."
To create an object of the "Dog" class, you would write:
Dog myDog;
This creates an object called "myDog" that belongs to the "Dog" class. You can then access the variables and methods of the object using the dot notation, like this:
myDog.breed = "Labrador";
myDog.age = 3;
myDog.weight = 15;
myDog.bark();
myDog.fetch();
Here's a more complete example of a class in C++:
class Dog {
public:
string breed;
int age;
int weight;
void bark() {
cout << "Woof!" << endl;
}
void fetch() {
cout << "Fetching..." << endl;
}
};
int main() {
Dog myDog;
myDog.breed = "Labrador";
myDog.age = 3;
myDog.weight = 15;
myDog.bark();
myDog.fetch();
return 0;
}
This program would output:
Woof!
Fetching...
2.Constructor And Destructor
In C++, a constructor is a special member function of a class that is executed whenever we create new objects of that class. The main purpose of a constructor is to initialize the object of a class by setting the values of data members.
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope or is explicitly deleted. The main purpose of a destructor is to release resources that were acquired by the object during its lifetime.
Here is an example of a class that has a constructor and a destructor:
class Point
{
private:
int x, y;
public:
// Constructor
Point(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
// Destructor
~Point()
{
// Release resources
}
// Other member functions
void move(int dx, int dy)
{
x += dx;
y += dy;
}
};
int main()
{
Point p1(1, 2); // Calls the constructor
p1.move(3, 4);
Point p2(5, 6); // Calls the constructor
p2.move(7, 8);
return 0; // Calls the destructor for p2 and then for p1
}
In this example, the Point class has a constructor that initializes the x and y data members of the object. It also has a destructor that releases any resources that were acquired by the object. The main function creates two objects of the Point class and calls the move member function on them. When the main function ends, the destructor is called for each object, in the reverse order of their creation.
Post a Comment