C++ Class and Objects | Find output programs | Set 4

This section contains the C++ find output programs with their explanations on C++ Class and Objects (set 4).
Submitted by Nidhi, on June 10, 2020

Program 1:

#include <iostream>
using namespace std;

class Sample {
    int X;
    int* const PTR = &X;

public:
    void set(int x);
    void print();
};

void Sample::set(int x)
{
    *PTR = x;
}

void Sample::print()
{
    cout << *PTR - EOF << " ";
}

int main()
{
    Sample S;

    S.set(10);
    S.print();

    return 0;
}

Output:

11

Explanation:

In the above program, we created class Sample that contain member X and a constant pointer PTR that contains the address of X, here we cannot relocate the pointer but we can change the value of X using pointer PTR.

Here, we defined two member functions set() and print() outside the class.

The set() function set the value to the data member X. and print() member function uses cout statement.

cout << *PTR-EOF << " ";

The value of EOF is -1 then 10- -1 = 11.

Thus, 11 will be printed on the console screen.

Program 2:

#include <iostream>
using namespace std;

class Sample {
    int X;
    int* const PTR = &X;

public:
    void set(int x);
    void print();
};

void Sample::set(int x)
{
    *PTR = x;
}

void Sample::print()
{
    cout << *PTR - EOF << " ";
}

int main()
{
    Sample* S;

    S->set(10);
    S->print();

    return 0;
}

Output:

Segmentation fault (core dumped)
OR
Runtime error

Explanation:

The above code will generate a runtime error because in the above program we created the pointer of the class but, we did not initialize pointer PTR with any object of the Sample class. If we try to access the member of the class Sample then it will generate a runtime error.

Program 3:

#include <iostream>
using namespace std;

class Sample {
    int X;
    int* const PTR = &X;

public:
    void set(int x);
    void print();
};

void Sample::set(int x)
{
    *PTR = x;
}

void Sample::print()
{
    cout << *PTR - EOF << " ";
}

int main()
{
    Sample* S = &(Sample());

    S->set(10);
    S->print();

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:25:27: error: taking address of temporary [-fpermissive]
     Sample* S = &(Sample());
                           ^

Explanation:

The above program will generate an error due to the below statement used in the main() function:

Sample *S = &(Sample());

Here we created a pointer of the class and tried to initialize with the object of the class, this is not the correct way. The correct way is,

Sample OB;
Sample *S = &OB;




Comments and Discussions!

Load comments ↻





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