Why do you use the const at the end of the method definition?

Asked 1 years ago, Updated 1 years ago, 113 views

Why are you using this? I'm confused

class Myclass
{
public:
    void print() const {}
};

c++ const declaration

2022-09-22 22:35

1 Answers

If you add the const keyword after the method,

class MyClass
{
private:
    int counter;
public:
    void Foo(){
        counter=0;
        std::cout << "Foo" << std::endl;
    }
    void Foo() const{
        //counter = 1; error because the value cannot be changed in //const function
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

Results are

Foo
Foo const
class MyClass
{
public:
    void Foo(){
        std::cout << "Foo" << std::endl;
        callByFoo();
    }

    void Foo() const{
        std::cout << "Foo const" << std::endl;
        The callByFoo(); //const function cannot call non-const methods. error
    }

    void callByFoo(){
        std::cout << "callByFoo" << std::endl;
    }
    void callByFoo() const
    {
        std::cout << "callByFoo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();

}

Results are

Foo
callByFoo
Foo const
callByFoo const


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.