And I really do want to be able to master them!
Does anyone have any good methods/ways to simply understand the logic behind it?
I am a beginner C++ coder with a little knowledge of CoboL language. Could anyone give me any good suggestions about them rather than just looking through C++ foundation books?
class foo
{
int a;
public:
foo(int x) : a(x) {}
};
int main()
{
int i = 1;
int j = 2;
foo x(1), y(2);
i + j; //correct
x + y; //incorrect, compiler does not know how to add foo objects
i = 5; //correct;
x = y; //incorect, compiler does not know how to assign foo objects
}
class foo
{
int a;
public:
foo(int x) : a(x) {}
int get() const {return a;}
//member operator overload. Assigment operators should be members
foo& operator=(const foo& other)
{
a = other.a;
return *this;
}
};
//Non-member overload
foo operator+(const foo& lhs, const foo& rhs)
{
return foo(lhs.get() + rhs.get());
}
int main()
{
int i = 1;
int j = 2;
foo x(1), y(2);
i + j; //correct
x + y; //works now
i = 5; //correct;
x = y; //works now
}
Now, what if we wanted to create our own 1024bit integer type and use it similarly? Well in C, define a struct to hold your data structure, and you'd create a set of functions that look like:
C++ allows you to create user defined types that act like built in types. So you can create a new class of object, int1024. The C++ language guarantees known behaviour when these things are created, destroyed, copied and moved using constructors, destructor and assignment operators.
You can also define your own + and - operators. This is called operator overloading. There's a whole bunch of operators that can be overloaded.
Putting it al together, the C++ equvalent of that C program would be:
1 2 3 4 5 6 7 8 9 10
int main()
{
int1024 a, b, c_sq;
a = 3;
b = 4;
c_sq = a*a + b*b;
return 0;
}
First is function overloading. There can be more than one function with same name, if they take different parameters. C does not have function overloading. Convenient; you don't have to come up with zillion names (foo, foof, food, fool, fooll, fooc) and you don't have to change all function calls if you change the type of a variable.
Operators are functions, but with syntactic sugar. You could write operator+(a, b), but you probably prefer a+b. That can make the code look almost like math.
C++ has user-defined types; (classes and structs). They don't have operators by default. Only the user (who defines the type) knows how to add up two objects (or whether it makes no sense). However, when the operators have been created, the type can be used conveniently. Math may not be of interest to you, but how about input and output (<< and >>)?