How do I overload...

Pls can I know how to overload the << operator?, to display all the displayable contents in a class?!?
Put a friend function in the class to allow your overloading function to access private members of the class. (If you only want to use public members, then don't worry about this step).

Then create a function external to the class that will handle this behavior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

class MyClass
{
  int a;
  int b;
public:
  MyClass() : a(0), b(1) {}
  friend std::ostream& operator << (std::ostream& o, MyClass c);
};

std::ostream& operator << (std::ostream& o, MyClass c)
{
    o << c.a << ' ' << c.b;
    return o;
}

int main()
{
	MyClass A;
	std::cout << A << std::endl;
}
0 1
Last edited on
What does MyClass() : a(0), b(1) {} mean?!?
It's the constructor. When you create an instance of MyClass, a is given the value 0 and b is given the value 1.
Last edited on
But why isn't it in the curly brackets{} ?
it's the shorter and better way to initialize.

int a = 0; can be declared as int a(0);


1
2
3
4
5
6
MyClass::MyClass()
{
    //body
    a = 0;
    b = 1;
}
can be written as
1
2
3
4
5
MyClass::MyClass()
: a(0), b(1)
{
    //body
}


this way both a and b are initialized before the constructor's body {} is called, so it is faster than assigning a and b in the body
Last edited on
Thank you all!!!
Topic archived. No new replies allowed.