C++ Programming: Functions & OOP
1. Functions in C++
A function is a block of code that performs a specific task. Functions allow us to reuse code: we define the code once and call it whenever it is needed.
#include <iostream>
using namespace std;
void myFunction() {
int x = 2;
int y = 5;
cout << "Sum of the two numbers is: " << x + y << endl;
}
int main() {
myFunction(); // Calling the function
return 0;
}
Output:
Sum of the two numbers is: 7
2. OOP Concepts in C++
OOP (Object-Oriented Programming) is a paradigm that uses Classes (blueprints) and Objects (instances). It provides a clear structure and helps keep code organized.
Note: These concepts apply to C++, as standard C does not support classes.
#include <iostream>
#include <string> // Required for string variables
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 << endl;
return 0;
}
Output:
15
Some text
Some text
3. Methods in C++
Methods are functions that belong to a class. They define the behavior of the objects created from that class.
#include <iostream>
using namespace std;
class MyClass {
public:
void myMethod() { // Method defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Output:
Hello World!
4. Parameters and Scope Resolution
Parameters allow you to pass data into methods. You can also define methods outside the class using the scope resolution operator (::).
#include <iostream>
using namespace std;
class Thermometer {
public:
// Method declaration
int convertToCelsius(int fahrenheit);
};
// Method definition outside the class
int Thermometer::convertToCelsius(int fahrenheit) {
return 5 * (fahrenheit - 32) / 9;
}
int main() {
Thermometer myObj;
// Passing -40 as a parameter
cout << "Result: " << myObj.convertToCelsius(-40);
return 0;
}
Output:
Result: -40