-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSoloLearn-cpp-notes.txt
10222 lines (8309 loc) · 312 KB
/
SoloLearn-cpp-notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
What is an Object
What is a Class
Example of a Class
Abstraction
Encapsulation
Example of Encapsulation
Constructors
Quiz
C++ 2 Module 1 Quiz
Code Project
Queue Management Part 1
More On Classes
Separate Files for Classes
Destructors
Selection Operator
Constant Objects
Member Initializers
Composition, Part 1
Composition, Part 2
The Friend Keyword
The This Keyword
Operator Overloading
C++ 2 Module 2 Quiz
Code Project
Queue Management Part 2
Inheritance & Polymorphism
Inheritance
Protected Members
Derived Class Constructor & Destructor
Polymorphism
Virtual Functions
Abstract Classes
Quiz
C++ 2 Module 3 Quiz
Code Project
Queue Management Part 3
Templates, Exceptions, and Files
Function Templates
Function Templates with Multiple Parameters
Class Templates
Template Specialization
Exceptions
More on Exceptions
Working with Files
More on Files
Quiz
C++ 2 Module 4 Quiz
######################################################################################
######################################################################################
## endroughxfer-urldump #1#
## <EOF><EOF> Intermediate C++ (SoloLearn) Volume 1
######################################################################################
######################################################################################
++=====================++
++=====================++ Classes & Objects:: What is an object?
What is an Object
Object Oriented Programming is a programming style that is intended to make thinking about programming closer to thinking about the real world.
In programming, objects are independent units, and each has its own identity, just as objects in the real world do.
An apple is an object; so is a mug. Each has its unique identity. It's possible to have two mugs that look identical, but they are still separate, unique objects.
===================================================================
Objects
An object might contain other objects but they're still different objects.
Objects also have characteristics that are used to describe them. For example, a car can be red or blue, a mug can be full or empty, and so on. These characteristics are also called attributes. An attribute describes the current state of an object.
Objects can have multiple attributes (the mug can be empty, red and large).
An object's state is independent of its type; a cup might be full of water, another might be empty.
===================================================================
Objects
In the real world, each object behaves in its own way. The car moves, the phone rings, and so on.
The same applies to objects - behavior is specific to the object's type.
So, the following three dimensions describe any object in object oriented programming: identity, attributes, behavior.
===================================================================
Objects
In programming, an object is self-contained, with its own identity. It is separate from other objects.
Each object has its own attributes, which describe its current state. Each exhibits its own behavior, which demonstrates what they can do.
img-component
In computing, objects aren't always representative of physical items.
For example, a programming object can represent a date, a time, a bank account. A bank account is not tangible; you can't see it or touch it, but it's still a well-defined object - it has its own identity, attributes, and behavior.
Tap Continue to dive right into Object Oriented Programming (OOP) with C++!
++=====================++
++=====================++ What is a Class?
===================================================================
What is a Class
Objects are created using classes, which are actually the focal point of OOP.
The class describes what the object will be, but is separate from the object itself.
In other words, a class can be described as an object's blueprint, description, or definition.
You can use the same class as a blueprint for creating multiple different objects. For example, in preparation to creating a new building, the architect creates a blueprint, which is used as a basis for actually building the structure. That same blueprint can be used to create multiple buildings.
Programming works in the same fashion. We first define a class, which becomes the blueprint for creating objects.
Each class has a name, and describes attributes and behavior.
In programming, the term type is used to refer to a class name: We're creating an object of a particular type.
Attributes are also referred to as properties or data.
===================================================================
Methods
Method is another term for a class' behavior. A method is basically a function that belongs to a class.
Methods are similar to functions - they are blocks of code that are called, and they can also perform actions and return values.
===================================================================
A Class Example
For example, if we are creating a banking program, we can give our class the following characteristics:
name: BankAccount
attributes: accountNumber, balance, dateOpened
behavior: open(), close(), deposit()
The class specifies that each object should have the defined attributes and behavior. However, it doesn't specify what the actual data is; it only provides a definition.
Once we've written the class, we can move on to create objects that are based on that class.
Each object is called an instance of a class. The process of creating objects is called instantiation.
Each object has its own identity, data, and behavior.
++=====================++
++=====================++ Example of a Class
===================================================================
Declaring a Class
Begin your class definition with the keyword class. Follow the keyword with the class name and the class body, enclosed in a set of curly braces.
The following code declares a class called BankAccount:
class BankAccount {
};
C++
A class definition must be followed by a semicolon.
===================================================================
Declaring a Class
Define all attributes and behavior (or members) in the body of the class, within curly braces.
You can also define an access specifier for members of the class.
A member that has been defined using the public keyword can be accessed from outside the class, as long as it's anywhere within the scope of the class object.
You can also designate a class' members as private or protected. This will be discussed in greater detail later in the course.
===================================================================
Creating a Class
Let's create a class with one public method, and have it print out "Hi".
class BankAccount {
public:
void sayHi() {
cout << "Hi" << endl;
}
};
C++
The next step is to instantiate an object of our BankAccount class, in the same way we define variables of a type, the difference being that our object's type will be BankAccount.
#include <iostream>
using namespace std;
class BankAccount {
public:
void sayHi() {
cout << "Hi" << endl;
}
};
int main()
{
BankAccount test;
test.sayHi();
}
Our object named test has all the members of the class defined.
Notice the dot separator (.) that is used to access and call the method of the object.
We must declare a class before using it, as we do with functions.
++=====================++
++=====================++ Abstraction
===================================================================
##Abstraction
Abstraction
Data abstraction is the concept of providing only essential information to the outside world. It's a process of representing essential features without including implementation details.
A good real-world example is a book: When you hear the term book, you don't know the exact specifics, i.e.: the page count, the color, the size, but you understand the idea of a book - the abstraction of the book.
The concept of abstraction is that we focus on essential qualities, rather than the specific characteristics of one particular example.
===================================================================
Abstraction
Abstraction means, that we can have an idea or a concept that is completely separate from any specific instance.
It is one of the fundamental building blocks of object oriented programming.
For example, when you use cout, you're actually using the cout object of the class ostream. This streams data to result in standard output.
cout << "Hello!" << endl;
C++
In this example, there is no need to understand how cout will display the text on the user's screen. The only thing you need to know to be able to use it is the public interface.
===================================================================
Abstraction
Abstraction allows us to write a single bank account class, and then create different objects based on the class, for individual bank accounts, rather than creating a separate class for each bank account.
img-component
Abstraction acts as a foundation for the other object orientation fundamentals, such as inheritance and polymorphism. These will be discussed later in the course.
++=====================++
++=====================++ Encapsulation
===================================================================
Encapsulation
Part of the meaning of the word encapsulation is the idea of "surrounding" an entity, not just to keep what's inside together, but also to protect it.
In object orientation, encapsulation means more than simply combining attributes and behavior together within a class; it also means restricting access to the inner workings of that class.
The key principle here is that an object only reveals what the other application components require to effectively run the application. All else is kept out of view.
This is called data hiding.
===================================================================
Encapsulation
For example, if we take our BankAccount class, we do not want some other part of our program to reach in and change the balance of any object, without going through the deposit() or withdraw() behaviors.
We should hide that attribute, control access to it, so it is accessible only by the object itself.
This way, the balance cannot be directly changed from outside of the object and is accessible only using its methods.
This is also known as "black boxing", which refers to closing the inner working zones of the object, except of the pieces that we want to make public.
This allows us to change attributes and implementation of methods without altering the overall program. For example, we can come back later and change the data type of the balance attribute.
In summary the benefits of encapsulation are:
- Control the way data is accessed or modified.
- Code is more flexible and easy to change with new requirements.
- Change one part of code without affecting other part of code.
++=====================++
++=====================++ Example of Encapsulation
===================================================================
Access Specifiers
Access specifiers are used to set access levels to particular members of the class.
The three levels of access specifiers are public, protected, and private.
A public member is accessible from outside the class, and anywhere within the scope of the class object.
For example: #include <iostream>
#include <string>
using namespace std;
class myClass {
public:
string name;
};
int main() {
myClass myObj;
myObj.name = "SoloLearn";
cout << myObj.name;
return 0;
}
The name attribute is public; it can be accessed and modified from outside the code.
Access modifiers only need to be declared once; multiple members can follow a single access modifier.
Notice the colon (:) that follows the public keyword.
===================================================================
Private
A private member cannot be accessed, or even viewed, from outside the class; it can be accessed only from within the class.
A public member function may be used to access the private members. For example:
===================================================================
#include <iostream>
#include <string>
using namespace std;
class myClass {
public:
void setName(string x) {
name = x;
}
private:
string name;
};
int main() {
myClass myObj;
myObj.setName("John");
return 0;
}
===================================================================
The name attribute is private and not accessible from the outside.
The public setName() method is used to set the name attribute.
If no access specifier is defined, all members of a class are set to private by default.
===================================================================
++=====================++
++=====================++
Access Specifiers
We can add another public method in order to get the value of the attribute.
class myClass {
public:
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
The getName() method returns the value of the private name attribute.
===================================================================
Access Specifiers
Putting it all together:
#include <iostream>
#include <string>
using namespace std;
class myClass {
public:
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
int main() {
myClass myObj;
myObj.setName("John");
cout << myObj.getName();
return 0;
}
We used encapsulation to hide the name attribute from the outside code. Then we provided access to it using public methods. Our class data can be read and modified only through those methods.
This allows for changes to the implementation of the methods and attributes, without affecting the outside code.
++=====================++
++=====================++ Abstraction
===================================================================
Abstraction
Data abstraction is the concept of providing only essential information to the outside world. It's a process of representing essential features without including implementation details.
A good real-world example is a book: When you hear the term book, you don't know the exact specifics, i.e.: the page count, the color, the size, but you understand the idea of a book - the abstraction of the book.
The concept of abstraction is that we focus on essential qualities, rather than the specific characteristics of one particular example.
===================================================================
Abstraction
Abstraction means, that we can have an idea or a concept that is completely separate from any specific instance.
It is one of the fundamental building blocks of object oriented programming.
For example, when you use cout, you're actually using the cout object of the class ostream. This streams data to result in standard output.
cout << "Hello!" << endl;
C++
In this example, there is no need to understand how cout will display the text on the user's screen. The only thing you need to know to be able to use it is the public interface.
===================================================================
Abstraction
Abstraction allows us to write a single bank account class, and then create different objects based on the class, for individual bank accounts, rather than creating a separate class for each bank account.
img-component
Abstraction acts as a foundation for the other object orientation fundamentals, such as inheritance and polymorphism. These will be discussed later in the course.
===================================================================
++=====================++
++=====================++ Constructors
Constructors
Class constructors are special member functions of a class. They are executed whenever new objects are created within that class.
The constructor's name is identical to that of the class. It has no return type, not even void.
For example:
#include <iostream>
using namespace std;
class myClass {
public:
myClass() {
cout <<"Hey";
}
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
int main() {
myClass myObj;
return 0;
}
Now, upon the creation of an object of type myClass, the constructor is automatically called.
===================================================================
Constructors
Constructors can be very useful for setting initial values for certain member variables.
A default constructor has no parameters. However, when needed, parameters can be added to a constructor. This makes it possible to assign an initial value to an object when it's created, as shown in the following example:
class myClass {
public:
myClass(string nm) {
setName(nm);
}
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
C++
We defined a constructor, that takes one parameter and assigns it to the name attribute using the setName() method.
++=====================++
++=====================++ Separate files for Deletion
Creating a New Class
It is generally a good practice to define your new classes in separate files. This makes maintaining and reading the code easier.
To do this, use the following steps in CodeBlocks:
Click File->New->Class...
Give your new class a name, uncheck "Has destructor" and check "Header and implementation file shall be in same folder", then click the "Create" button.
img-component
Note that two new files have been added to your project:
img-component
The new files act as templates for our new class.
- MyClass.h is the header file.
- MyClass.cpp is the source file.
++=====================++
++=====================++
Source & Header
The header file (.h) holds the function declarations (prototypes) and variable declarations.
It currently includes a template for our new MyClass class, with one default constructor.
MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
MyClass();
protected:
private:
};
#endif // MYCLASS_H
C++
The implementation of the class and its methods go into the source file (.cpp).
Currently it includes just an empty constructor.
MyClass.cpp
#include "MyClass.h"
MyClass::MyClass()
{
//ctor
}
C++
The #ifndef and #define statements in the header file will be discussed in the upcoming lessons.
===================================================================
Scope Resolution Operator
The double colon in the source file (.cpp) is called the scope resolution operator, and it's used for the constructor definition:
#include "MyClass.h"
MyClass::MyClass()
{
//ctor
}
C++
The scope resolution operator is used to define a particular class' member functions, which have already been declared. Remember that we defined the constructor prototype in the header file.
So, basically, MyClass::MyClass() refers to the MyClass() member function - or, in this case, constructor - of the MyClass class.
===================================================================
Source & Header
To use our classes in our main, we need to include the header file.
For example, to use our newly created MyClass in main:
#include <iostream>
#include "MyClass.h"
using namespace std;
int main() {
MyClass obj;
}
C++
The header declares "what" a class (or whatever is being implemented) will do, while the cpp source file defines "how" it will perform those features.
===================================================================
++=====================++
++=====================++ Destructors
Destructors
Remember constructors? They're special member functions that are automatically called when an object is created.
Destructors are special functions, as well. They're called when an object is destroyed or deleted.
Objects are destroyed when they go out of scope, or whenever the delete expression is applied to a pointer directed at an object of a class.
===================================================================
Destructors
The name of a destructor will be exactly the same as the class, only prefixed with a tilde (~). A destructor can't return a value or take any parameters.
class MyClass {
public:
~MyClass() {
// some code
}
};
C++
Destructors can be very useful for releasing resources before coming out of the program. This can include closing files, releasing memory, and so on.
===================================================================
Destructors
For example, let's declare a destructor for our MyClass class, in its header file MyClass.h:
class MyClass
{
public:
MyClass();
~MyClass();
};
C++
Declare a destructor for our MyClass class.
===================================================================
Destructors
After declaring the destructor in the header file, we can write the implementation in the source file MyClass.cpp:
#include "MyClass.h"
#include <iostream>
using namespace std;
MyClass::MyClass()
{
cout<<"Constructor"<<endl;
}
MyClass::~MyClass()
{
cout<<"Destructor"<<endl;
}
Note that we included the <iostream> header, so that we can use cout.
===================================================================
Destructors
Since destructors can't take parameters, they also can't be overloaded.
Each class will have just one destructor.
Defining a destructor is not mandatory; if you don't need one, you don't have to define one.
===================================================================
Destructors
Let's return to our main.
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass();
~MyClass();
};
MyClass::MyClass()
{
cout<<"Constructor"<<endl;
}
MyClass::~MyClass()
{
cout<<"Destructor"<<endl;
}
int main() {
MyClass obj;
}
We included the class' header file and then created an object of that type.
This returns the following output:
Constructor
Destructor
C++
When the program runs, it first creates the object and calls the constructor. The object is deleted and the destructor is called when the program's execution is completed.
Remember that we printed "Constructor" from the constructor and "Destructor" from the destructor.
===================================================================
++=====================++
++=====================++ Selection Operator
#ifndef & #define
We created separate header and source files for our class, which resulted in this header file.
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
MyClass();
protected:
private:
};
#endif // MYCLASS_H
C++
ifndef stands for "if not defined". The first pair of statements tells the program to define the MyClass header file if it has not been defined already.
endif ends the condition.
This prevents a header file from being included more than once within one file.
===================================================================
Member Functions
Let's create a sample function called myPrint() in our class.
MyClass.h
class MyClass
{
public:
MyClass();
void myPrint();
};
C++
MyClass.cpp
#include "MyClass.h"
#include <iostream>
using namespace std;
MyClass::MyClass() {
}
void MyClass::myPrint() {
cout <<"Hello"<<endl;
}
C++
Since myPrint() is a regular member function, it's necessary to specify its return type in both the declaration and the definition.
===================================================================
Dot Operator
Next, we'll create an object of the type MyClass, and call its myPrint() function using the dot (.) operator:
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass();
void myPrint();
};
MyClass::MyClass() {
}
void MyClass::myPrint() {
cout <<"Hello"<<endl;
}
int main() {
MyClass obj;
obj.myPrint();
}
Run the code and see how it works!
OUTPUT
Hello
===================================================================
Pointers
We can also use a pointer to access the object's members.
The following pointer points to the obj object:
MyClass obj;
MyClass *ptr = &obj;
C++
The type of the pointer is MyClass, as it points to an object of that type.
===================================================================
Selection Operator
The arrow member selection operator (->) is used to access an object's members with a pointer.
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass();
void myPrint();
};
MyClass::MyClass() {
}
void MyClass::myPrint() {
cout <<"Hello"<<endl;
}
int main() {
MyClass obj;
MyClass *ptr = &obj;
ptr->myPrint();
}
When working with an object, use the dot member selection operator (.).
When working with a pointer to the object, use the arrow member selection operator (->).
===================================================================
++=====================++
++=====================++ Constant Objects
Constants
A constant is an expression with a fixed value. It cannot be changed while the program is running.
Use the const keyword to define a constant variable.
const int x = 42;
C++
All constant variables must be initialized at the time of their creation.
===================================================================
Constant Objects
As with the built-in data types, we can make class objects constant by using the const keyword.
const MyClass obj;
C++
All const variables must be initialized when they're created. In the case of classes, this initialization is done via constructors. If a class is not initialized using a parameterized constructor, a public default constructor must be provided - if no public default constructor is provided, a compiler error will occur.
Once a const class object has been initialized via the constructor, you cannot modify the object's member variables. This includes both directly making changes to public member variables and calling member functions that set the value of member variables.
When you've used const to declare an object, you can't change its data members during the object's lifetime.
===================================================================
Constant Objects
Only non-const objects can call non-const functions.
A constant object can't call regular functions. Hence, for a constant object to work you need a constant function.
To specify a function as a const member, the const keyword must follow the function prototype, outside of its parameters' closing parenthesis. For const member functions that are defined outside of the class definition, the const keyword must be used on both the function prototype and definition. For example:
MyClass.h
class MyClass
{
public:
void myPrint() const;
};
C++
MyClass.cpp
#include "MyClass.h"
#include <iostream>
using namespace std;
void MyClass::myPrint() const {
cout <<"Hello"<<endl;
}
C++
Now the myPrint() function is a constant member function. As such, it can be called by our constant object:
#include <iostream>
using namespace std;
class MyClass
{
public:
void myPrint() const;
};
void MyClass::myPrint() const {
cout <<"Hello"<<endl;
}
int main() {
const MyClass obj;
obj.myPrint();
}
OUTPUT
Hello
===================================================================
Constant Objects
Attempting to call a regular function from a constant object results in an error.
In addition, a compiler error is generated when any const member function attempts to change a member variable or to call a non-const member function.
Defining constant objects and functions ensures that corresponding data members cannot be unexpectedly modified.
===================================================================
++=====================++
++=====================++ Member Initializers
Member Initializers
Recall that constants are variables that cannot be changed, and that all const variables must be initialized at time of creation.
C++ provides a handy syntax for initializing members of the class called the member initializer list (also called a constructor initializer).
===================================================================
Member Initializers
Consider the following class:
class MyClass {
public:
MyClass(int a, int b) {
regVar = a;
constVar = b;
}
private:
int regVar;
const int constVar;
};
C++
This class has two member variables, regVar and constVar. It also has a constructor that takes two parameters, which are used to initialize the member variables.
Running this code returns an error, because one of its member variables is a constant, which cannot be assigned a value after declaration.
In cases like this one, a member initialization list can be used to assign values to the member variables.
class MyClass {
public:
MyClass(int a, int b)
: regVar(a), constVar(b)
{
}
private:
int regVar;
const int constVar;
};
C++
Note that in the syntax, the initialization list follows the constructor parameters. The list begins with a colon (:), and then lists each variable to be initialized, along with the value for that variable, with a comma to separate them.
Use the syntax variable(value) to assign values.
The initialization list eliminates the need to place explicit assignments in the constructor body. Also, the initialization list does not end with a semicolon.
===================================================================
Member Initializers
Let's write the previous example using separate header and source files.
MyClass.h
class MyClass {
public:
MyClass(int a, int b);
private:
int regVar;
const int constVar;
};
C++
MyClass.cpp
MyClass::MyClass(int a, int b)
: regVar(a), constVar(b)
{
cout << regVar << endl;
cout << constVar << endl;
}
C++
We have added cout statements in the constructor to print the values of the member variables.
Our next step is to create an object of our class in main, and use the constructor to assign values.
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass(int a, int b);
private:
int regVar;
const int constVar;
};
MyClass::MyClass(int a, int b)
: regVar(a), constVar(b)
{
cout << regVar << endl;
cout << constVar << endl;
}
int main() {
MyClass obj(42, 33);
}
OUTPUT
42
33
The constructor is used to create the object, assigning two parameters to the member variables via the member initialization list.
===================================================================
Member Initializers
The member initialization list may be used for regular variables, and must be used for constant variables.
Even in cases in which member variables are not constant, it makes good sense to use the member initializer syntax.
===================================================================
++=====================++
++=====================++ Composition Part 1
Composition
In the real world, complex objects are typically built using smaller, simpler objects. For example, a car is assembled using a metal frame, an engine, tires, and a large number of other parts. This process is called composition.
In C++, object composition involves using classes as member variables in other classes.
This sample program demonstrates composition in action. It contains Person and Birthday classes, and each Person will have a Birthday object as its member.
Birthday:
class Birthday {
public:
Birthday(int m, int d, int y)
: month(m), day(d), year(y)
{
}
private:
int month;
int day;
int year;
};
C++
Our Birthday class has three member variables. It also has a constructor that initializes the members using a member initialization list.
The class was declared in a single file for the sake of simplicity. Alternatively, you could use header and source files.
===================================================================
Composition
Let's also add a printDate() function to our Birthday class:
class Birthday {
public:
Birthday(int m, int d, int y)
: month(m), day(d), year(y)
{
}
void printDate()
{
cout<<month<<"/"<<day
<<"/"<<year<<endl;
}