Cannot have cv - qualifier



I'm trying to practice using const. I was taught that I could use const with functions if I don't want them to change, but when I try to use const I get the error. void printext() cannot have cv - qualifier. But when i remove const the code runs fine. Why does this error occur? what did I do wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;


void printText() const { cout << "Supreme" << endl;}

int main()
{

    printText();


    return 0;
}
Last edited on
closed account (E0p9LyTq)
Only class functions can have const qualifiers.
Why does this error occur?
Because there is no sence to have cv-qualified freestanding function.

Only thing you can append cv-qualifiers in freestanding function (aside from obvious things like variables in function body) is its parameters:
1
2
3
4
5
6
7
8
#include <iostream>

void printText(const char* text) { std::cout << text << std::endl;}

int main()
{
    printText("Supreme");
}


YOu can have cv-qualified member functions:
1
2
3
4
5
6
7
8
9
10
struct foo
{
    void doNothing() const {}
};

int main()
{
    const foo bar;
    bar.doNothing();
}
It is made possible because member functions have hidden parameter: pointer to object you call them with. that const applied to this hidden argument.
Topic archived. No new replies allowed.