OOP
UNIT-2Pointers, Arrays, Dynamic allocation OperatorCreate an object and a class Create a ClassTo create a class, use the class keyword:ExampleCreate a class called "MyClass":class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};Example explainedThe class keyword is used to create a class called MyClass. The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later. Inside the class, there is an integer variable myNum and a string variable myString. When variables are declared within a class, they are called attributes. At last, end the class definition with a semicolon ;. Create an ObjectIn C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.To create an object of MyClass, specify the class name, followed by the object name.To access the class attributes (myNum and myString), use the dot syntax (.) on the object:ExampleCreate an object called "myObj" and access the attributes: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 attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}2. Explain in detail Visibility/Access Modifiers with examplesData hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.class Base { public: // public members go here protected: // protected members go here private: // private members go here };The public MembersA public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example −#include <iostream> using namespace std; class Line { public: double length; void setLength( double len ); double getLength( void );}; // Member functions definitionsdouble Line::getLength(void) { return length ;} void Line::setLength( double len) { length = len;} // Main function for the programint main() { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; // set line length without member function line.length = 10.0; // OK: because length is public cout << "Length of line : " << line.length <<endl; return 0;}When the above code is compiled and executed, it produces the following result −Length of line : 6Length of line : 10The private MembersA private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void );};Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.#include <iostream> using namespace std; class Box { public: double length; void setWidth( double wid ); double getWidth( void ); private: double width;}; // Member functions definitionsdouble Box::getWidth(void) { return width ;} void Box::setWidth( double wid ) { width = wid;} // Main function for the programint main() { Box box; // set box length without member function box.length = 10.0; // OK: because length is public cout << "Length of box : " << box.length <<endl; // set box width without member function // box.width = 10.0; // Error: because width is private box.setWidth(10.0); // Use member function to set it. cout << "Width of box : " << box.getWidth() <<endl; return 0;}When the above code is compiled and executed, it produces the following result −Length of box : 10Width of box : 10The protected MembersA protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box.Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox. #include <iostream>using namespace std; class Box { protected: double width;}; class SmallBox:Box { // SmallBox is the derived class. public: void setSmallWidth( double wid ); double getSmallWidth( void );}; // Member functions of child classdouble SmallBox::getSmallWidth(void) { return width ;} void SmallBox::setSmallWidth( double wid ) { width = wid;} // Main function for the programint main() { SmallBox box; // set box width using member function box.setSmallWidth(5.0); cout << "Width of box : "<< box.getSmallWidth() << endl; return 0;}When the above code is compiled and executed, it produces the following result −Width of box : 5 3. Explain Encapsulation in details with examplesAll C++ programs are composed of the following two fundamental elements −Program statements (code) − This is the part of a program that performs actions and they are called functions. Program data − The data is the information of the program which gets affected by the program functions. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example −class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box};The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program.Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible.Data Encapsulation ExampleAny C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example –#include <iostream>using namespace std; class Adder { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total;}; int main() { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0;}When the above code is compiled and executed, it produces the following result −Total 60Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.Designing StrategyMost of us have learnt to make class members private by default unless we really need to expose them. That's just good encapsulation.This is applied most frequently to data members, but it applies equally to all members, including virtual functions.4. Explain Methods: Adding a Method to ClassMethods are functions that belongs to the class.There are two ways to define functions that belongs to a class:Inside class definition Outside class definition In the following example, we define a function inside the class, and we name it "myMethod".Note: You access methods just like you access attributes; by creating an object of the class and by using the dot syntax (.):Inside Exampleclass MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by specifiying the name of the class, followed the scope resolution :: operator, followed by the name of the function:Outside Exampleclass MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}ParametersYou can also add parameters: Example#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}5. Explain Returning a ValueA C++ program can be made easier to read and maintain by using references rather than pointers. A C++ function can return a reference in a similar way as it returns a pointer.When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement. For example, consider this simple program − #include <iostream>#include <ctime> using namespace std; double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues( int i ) { return vals[i]; // return a reference to the ith element} // main function to call above defined function.int main () { cout << "Value before change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } setValues(1) = 20.23; // change 2nd element setValues(3) = 70.8; // change 4th element cout << "Value after change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } return 0;}When the above code is compiled together and executed, it produces the following result −Value before changevals[0] = 10.1vals[1] = 12.6vals[2] = 33.1vals[3] = 24.1vals[4] = 50Value after changevals[0] = 10.1vals[1] = 20.23vals[2] = 33.1vals[3] = 70.8vals[4] = 50When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.int& func() { int q; //! return q; // Compile time error static int x; return x; // Safe, x lives outside this scope} 6. Explain Recursivity Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!) the mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:
Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since, otherwise, the function would perform an infinite recursive loop, in which once it arrived to 0, it would continue multiplying by all the negative numbers (probably provoking a stack overflow at some point during runtime).7. Explain The ‘this’ KeywordIn C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.It can be used to pass current object as a parameter to another method. It can be used to refer current class instance variable. It can be used to declare indexers. C++ this Pointer ExampleLet's see the example of this keyword in C++ that refers to the fields of current class.#include <iostream> using namespace std; class Employee { public: int id; //data member (also instance variable) string name; //data member(also instance variable) float salary; Employee(int id, string name, float salary) { this->id = id; this->name = name; this->salary = salary; } void display() { cout<<id<<" "<<name<<" "<<salary<<endl; } }; int main(void) { Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee e1.display(); e2.display(); return 0; } Output:101 Sonoo 890000102 Nakul 59000 8. Explain Function OverloadingFunction Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++. In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for the same action.C++ Function Overloading ExampleLet's see the simple example of function overloading where we are changing number of arguments of add() method.// program of function overloading when number of arguments vary.#include <iostream> using namespace std; class Cal { public: static int add(int a,int b){ return a + b; } static int add(int a, int b, int c) { return a + b + c; } }; int main(void) { Cal C; // class object declaration. cout<<C.add(10, 20)<<endl; cout<<C.add(12, 20, 23); return 0; } Output:3055Let's see the simple example when the type of the arguments vary.// Program of function overloading with different types of arguments.#include<iostream> using namespace std; int mul(int,int); float mul(float,int); int mul(int a,int b) { return a*b; } float mul(double x, int y) { return x*y; } int main() { int r1 = mul(6,7); float r2 = mul(0.2,3); std::cout << "r1 is : " <<r1<< std::endl; std::cout <<"r2 is : " <<r2<< std::endl; return 0; } Output:r1 is : 42r2 is : 0.6 9. Explain Operators OverloadingOperator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.The advantage of Operators overloading is to perform different operations on the same operand.Operator that cannot be overloaded are as follows:Scope operator (::) Sizeof member selector(.) member pointer selector(*) ternary operator(?:) Syntax of Operator Overloadingreturn_type class_name : : operator op(argument_list) { // body of the function. } Where the return type is the type of value returned by the function. class_name is the name of the class.operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.Rules for Operator OverloadingExisting operators can only be overloaded, but the new operators cannot be overloaded. The overloaded operator contains atleast one operand of the user-defined data type. We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators. When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument. When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments. 10. Explain Array of ObjectsLike array of other user-defined data types, an array of type class can also be created. The array of type class contains the objects of the class as its individual elements. Thus, an array of a class type is also known as an array of objects. An array of objects is declared in the same way as an array of any built-in data type. Syntax:class_name array_name [size] ;Example:#include <iostream> class MyClass { int x; public: void setX(int i) { x = i; } int getX() { return x; } }; void main() { MyClass obs[4]; int i; for(i=0; i < 4; i++) obs[i].setX(i); for(i=0; i < 4; i++) cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n"; getch(); }Output:obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};Example explained
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 attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}2. Explain in detail Visibility/Access Modifiers with examplesData hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.class Base { public: // public members go here protected: // protected members go here private: // private members go here };The public MembersA public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example −#include <iostream> using namespace std; class Line { public: double length; void setLength( double len ); double getLength( void );}; // Member functions definitionsdouble Line::getLength(void) { return length ;} void Line::setLength( double len) { length = len;} // Main function for the programint main() { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; // set line length without member function line.length = 10.0; // OK: because length is public cout << "Length of line : " << line.length <<endl; return 0;}When the above code is compiled and executed, it produces the following result −Length of line : 6Length of line : 10The private MembersA private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void );};Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.#include <iostream> using namespace std; class Box { public: double length; void setWidth( double wid ); double getWidth( void ); private: double width;}; // Member functions definitionsdouble Box::getWidth(void) { return width ;} void Box::setWidth( double wid ) { width = wid;} // Main function for the programint main() { Box box; // set box length without member function box.length = 10.0; // OK: because length is public cout << "Length of box : " << box.length <<endl; // set box width without member function // box.width = 10.0; // Error: because width is private box.setWidth(10.0); // Use member function to set it. cout << "Width of box : " << box.getWidth() <<endl; return 0;}When the above code is compiled and executed, it produces the following result −Length of box : 10Width of box : 10The protected MembersA protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box.Following example is similar to above example and here width member will be accessible by any member function of its derived class SmallBox. #include <iostream>using namespace std; class Box { protected: double width;}; class SmallBox:Box { // SmallBox is the derived class. public: void setSmallWidth( double wid ); double getSmallWidth( void );}; // Member functions of child classdouble SmallBox::getSmallWidth(void) { return width ;} void SmallBox::setSmallWidth( double wid ) { width = wid;} // Main function for the programint main() { SmallBox box; // set box width using member function box.setSmallWidth(5.0); cout << "Width of box : "<< box.getSmallWidth() << endl; return 0;}When the above code is compiled and executed, it produces the following result −Width of box : 5 3. Explain Encapsulation in details with examplesAll C++ programs are composed of the following two fundamental elements −
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by specifiying the name of the class, followed the scope resolution :: operator, followed by the name of the function:Outside Exampleclass MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}ParametersYou can also add parameters: Example#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}5. Explain Returning a ValueA C++ program can be made easier to read and maintain by using references rather than pointers. A C++ function can return a reference in a similar way as it returns a pointer.When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement. For example, consider this simple program − #include <iostream>#include <ctime> using namespace std; double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues( int i ) { return vals[i]; // return a reference to the ith element} // main function to call above defined function.int main () { cout << "Value before change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } setValues(1) = 20.23; // change 2nd element setValues(3) = 70.8; // change 4th element cout << "Value after change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } return 0;}When the above code is compiled together and executed, it produces the following result −Value before changevals[0] = 10.1vals[1] = 12.6vals[2] = 33.1vals[3] = 24.1vals[4] = 50Value after changevals[0] = 10.1vals[1] = 20.23vals[2] = 33.1vals[3] = 70.8vals[4] = 50When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.int& func() { int q; //! return q; // Compile time error static int x; return x; // Safe, x lives outside this scope} 6. Explain Recursivity Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!) the mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:
1 | // factorial calculator #include <iostream> using namespace std;
long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return 1; }
int main () { long number = 9; cout << number << "! = " << factorial (number); return 0; } |
|
|
Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since, otherwise, the function would perform an infinite recursive loop, in which once it arrived to 0, it would continue multiplying by all the negative numbers (probably provoking a stack overflow at some point during runtime).7. Explain The ‘this’ KeywordIn C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
0 matching results found