C++ const Keyword | Find output programs | Set 1

This section contains the C++ find output programs with their explanations on const Keyword (set 1).
Submitted by Nidhi, on June 04, 2020

Program 1:

#include <iostream>
using namespace std;

void fun(int& A) const
{
    A = 10;
}

int main()
{
    int X = 0;

    fun(X);

    cout << X;

    return 0;
}

Output:

[Error] non-member function 'void fun(int)' cannot have const qualifier.

Explanation:

The above code will generate an error because we cannot define, the non-member function as a const. Without a const keyword the above code will work fine.

Program 2:

#include <iostream>
using namespace std;

int main()
{
    const int X = 0;
    int* ptr;

    ptr = &X;
    *ptr = 10;

    cout << X;

    return 0;
}

Output:

error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive] ptr = &X;

Explanation:

The above program will generate an error in C++, C++ does not allow modification in a constant using pointer, but we can modify the value of a constant in C language. The below program in C language will work fine.

#include <stdio.h>

int main()
{
    const int X = 0;
    int* ptr;

    ptr = &X;
    *ptr = 10;

    printf("%d", X);

    return 0;
}

Program may run on C language compiler, but it is not a standard that we can change the constant. In C language compiler – it can be changed through the pointer.

Program 3:

#include <iostream>
using namespace std;

class Sample {
    const int A;
    const int B;

public:
    Sample(): A(10), B(20)
    {
    }
    void print()
    {
        cout << A << " " << B;
    }
};

int main()
{
    Sample S;

    S.print();

    return 0;
}

Output:

10 20

Explanation:

The above code will print "10 20" on the console screen.

Let's understand the program step by step.

Here we created a class Sample that contains two const data members A and B. As we know that we can assign the values of constant at the time of declaration. But here we use the concept of member initialize list.

Sample ():A(10),B(20)
{
}

We can assign value to const data members using the member initialize list. We can initialize members by a colon (:) with members and value in the constructor.

Here we also defined a print() member function, which is used to print values of data members.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.