Posts

Showing posts with the label Classes and Objects

Operator Overloading in C++

Image
Operator Overloading in C++ The meaning of an operator is always same for variable of basic types like: int, float, double etc. For example: To add two integers,  +  operator is used. However, for user-defined types (like: objects), you can redefine the way operator works. For example: If there are two objects of a class that contains string as its data members. You can redefine the meaning of + operator and use it to concatenate those strings. This feature in C++ programming that allows programmer to redefine the meaning of an operator (when they operate on class objects) is known as operator overloading. Why is operator overloading used? You can write any C++ program without the knowledge of operator overloading. However, operator operating are profoundly used by programmers to make program intuitive. For example, You can replace the code like: calculation = add(multiply(a, b),divide(a, b)); to calculation = (a*b)+(a/b); How to overload o...

in C++ How to pass and return an object from a function?

Image
 in C++ How to pass and return an object from a function? In C++ programming,   objects can be passed to a function in a similar way as structures . How to pass objects to a function? Example 1: Pass Objects to Function C++ program to add two complex numbers by passing objects to a function. #include <iostream> using namespace std ; class Complex { private : int real ; int imag ; public : Complex (): real ( 0 ), imag ( 0 ) { } void readData () { cout << "Enter real and imaginary number respectively:" << endl ; cin >> real >> imag ; } void addComplexNumbers ( Complex comp1 , Complex comp2 ) { // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); real = comp1 . real + comp2 . real ; // imag represents the ima...