2. Overloading operators: First, let me see if i am understanding this. You need to overload operators when you are using them with your own classes. So do i need to rewrite the function for for each class i use them with. Also, how do i write the function and what parameters do i use.
No, sah. You can overload operators, but there's no case when you really need to unless you're fiddling with something (some api or library) that demands a class with a specific operator overload.
class Example {
public:
Example(int a, int b, int c, int d) {
ary[0] = a;
ary[1] = b;
ary[2] = c;
ary[3] = d;
}
int getNumberAtIndex(size_t index) {
return ary[index];
}
int addToAllNumbers(int valueToAdd) {
for(int i = 0; i < sizeof(ary); ++i) {
ary[i] += valueToAdd;
}
}
private:
int ary[4];
};
Example ex(1, 2, 3, 4);
ex.addToAllNumbers(7);
int theThirdAryVal = ex.getNumberAtIndex(2);
You know how that works, yes?
You can call 'getNumberAtIndex()' to grab a value from the array. Well:
class Example {
public:
Example(int a, int b, int c, int d) {
ary[0] = a;
ary[1] = b;
ary[2] = c;
ary[3] = d;
}
int operator[](size_t index) {
return ary[index];
}
//do not do this (see notes after code)
int operator+(int valueToAdd) {
for(int i = 0; i < sizeof(ary); ++i) {
ary[i] += valueToAdd;
}
}
private:
int ary[4];
};
Example ex(1, 2, 3, 4);
ex + 7;
int theThirdAryVal = ex[2];
That's just another way of doing the same thing. A word of advice - only use operator overloads when the result of invoking the overload function would be obvious to someone else using your class, even if they don't read your documentation. Sometimes people do some really outrageous stuff with operator overloads and can create some really awesome bugs. Operator overloading is more or less a way of providing some 'syntactic sugar' for your class. Too much sugar rots your teeth. There's a running gag on this forum about overloading the comma operator. A class with an overloaded comma would call that function whenever you try to use it in an array or a list of arguments!
3. Copy constructor: what purpose do they serve and how to i write the/ implement them.
The copy constructor is used to replicate an object. If you don't specify one (or disable it by prototyping it but not implementing it) then the compiler will create one for you on the sly. Example:
class Thingy {
public:
//This is a constructor (explicit prevents a single-arg ctor from becoming a copy ctor)
explicit Thingy(int val) {
myval = val;
}
//This is a copy constructor.
Thingy(Thingy& other) {
myval = other.myval;
cout << "Copied!" << endl;
}
private:
int myval;
};
Thingy a(7);
Thingy b = a; //will print "Copied!"
//the 'myval' of b is 7
You should disable the copy ctor if you don't want to use it by declaring it in the private section and then not defining it.