Hi,
I have started studying c++ from the book "thinking in c++" I am at the chapter no 8 now, this is the hardest to understand so far. I have many confusions.
1st one is initializing the cons data member by using constructor,efore the constructor body starts , i didn't understand exactly why but the author c++ data members can only be intialized by this way , he shows the following example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std
class fred {
constint size;
public :
fred(int sz);
void print();
};
fred :: fred(int sz) : size(sz){}
void fred::print(){cout << size <<endl;}
int main()
{
fred a(1),b(2),c(3);
a.print(),b.print(),c.print();
}
in the next example he shows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std
class B {
int i;
public :
B(int i);
void print();
};
B :: B(int ii) : ii(i){}
void B::print(){cout << i <<endl;}
int main()
{
B a(1),b(2);
float pi(3.14159);
a.print(),b.print();
cout << pi << endl;
}
My confusion is how can float take argument like that when it is not a part of the class and second is there is no const member in this class still he is defining constructor like this to show that even built in can be treated as they have constructors but then why do we write like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class a
{
a(int i);
}
a :: a(int y)
{
i=y;
}
/*
why do not we always write like this so that we follow one procedure always no matter what
class a
{
a(int i);
}
a :: a(int y) : i(y){}
*/
About second question: That is one of two method of initialisation which existed before C++11, foo bar(baz); and foo bar = baz; are almost equivalent and actually same for built-in types.
The author says suppose we write like this const int * pp , it means the pointer is pointing to a constant integer which can not be changed.
In one of the exercises he says write two pointers to const long which points to an array of long. Demonstrate that you can increment or decrement but you can't change what it points to
My confusion is it should throw error when I try to assign a new value to arr[1], as we can not change what the pointer points to but it doesn't and gets compiled and shows output perfectly. Can someone explain why
or is there something I have missed understood?