Post

C++ Const Keyword

const with functions

Reference: Video

Using const in methods examples, and can be used for more efficiency.

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
class Dog {
    // Class Memebers
    int age;
    string name;

    public:
    Dog() {age =3; name = "dummy";}
    
    // Const parameter
    void setAge (const int& a ) {age = a;} // Correct[ pass by reference and can't be changed]
    void setAge (const int a ) {age = a;} // const is not useful here
    void setAge (int a ) {age = a;} // similar

    //  Const return value
    const string& getName() {return name;}; // pass by reference "more efficient"

    //const function [Means it will not modify any members of the class]
    void printDogName() const {
        cout << getName() << "const" << endl; // const functions can only called const functions
    }
    // Overload const function (will be called if instance of the class is const)
    void printDogName() {
        cout << name << "non-const" << endl; // const functions can only called const functions
    } 
     
}

int main(){
    // Call regular
    Dog d;
    d.printDogName();

    // Call overloaded 
    const Dog d2;
    d2.printDogName();
    }


This post is licensed under CC BY 4.0 by the author.