Day 11 Functions in Class
Day 11 Functions in Class
FUNCTION IN CLASS:
A function in a class refers to a member function or method that is defined within
a class. These functions are associated with an object of the class and can access
and modify the class's data members and perform specific operations related to the
class.
Syntax:
class ClassName {
public:
return_type functionName(parameters) {
// Function body
};
Explanation:
ClassName: The name of the class to which the function belongs.
return_type: The data type of the value returned by the function (use void if the
function does not return any value).
functionName: The name of the function.
parameters: The input parameters that the function may take (if any).
Function body: The set of statements that make up the function's functionality.
PROGRAM:
#include <iostream>
class MyClass {
int main() {
MyClass obj;
obj.sayHello();
return 0;
}
OUTPUT:
Hello from MyClass!
EXPLANATION:
In this example, we define a class MyClass with a public member function sayHello().
The sayHello() function is a member of MyClass and is declared within the class
definition.
The sayHello() function simply prints the message "Hello from MyClass!" to the
console using std::cout.
In the main() function, we create an object of the class MyClass called obj:
We call the sayHello() function on the obj object using the dot operator (.) to access the
member functions of the class. This results in printing the message "Hello from
MyClass!" to the console.
Syntax:
namespace_name::variable_name;
class_name::static_member;
PROGRAM:
#include <iostream>
int main() {
int x = 15; // Define a local integer variable x within main
OUTPUT:
Value of x in main: 15
Value of global x: 10
EXPLANATION:
In this example, we have a namespace called MyNamespace, and it contains a
variable x and a function display(). We also have a global variable x outside of the
namespace, and a local variable x inside the main() function.
1. int x = 5; - This x variable is defined inside the MyNamespace namespace.
2. void display() - This function is defined inside the MyNamespace namespace and
displays the value of the variable x inside the namespace.
3. int x = 10; - This x variable is defined in the global scope, outside of any function
or namespace.
5. int x = 15; - This x variable is defined inside the main() function, and it shadows
the global variable x.
6. std::cout << "Value of x in main: " << x << std::endl; - This line prints the value of
the local variable x, which is 15.
7. std::cout << "Value of global x: " << ::x << std::endl; - The scope resolution operator
:: is used here to access the global variable x outside the main() function, and it
prints the value of the global variable x, which is 10.