C++
OOP
C++ What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and functions.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code
C++ Classes/Objects
Classes and objects are the two main aspects of object-oriented programming.
Everything in C++ is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class.
These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an
object constructor, or a "blueprint" for creating objects.
Look at the following illustration to see the difference between class and objects:
Create a Class
OBJECTS
CLASS Apple
Fruits Mango
Banana
To create a class, use the class keyword:
Example 1
#include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Example 2
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Testing
//C++ program to shut down the system in Windows OS
#include <iostream>
#include <stdlib.h>
Using namespace std;
int main()
{
system("c:\\windows\\system32\\shutdown /i");
return 0;
}