Q:

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

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Class and Objects (set 2).

Program 1:

#include <iostream>
using namespace std;

class Sample {
    int A = 10;
    int B = 20;

protected:
    void print()
    {
        cout << A << " " << B;
    }
};

int main()
{
    Sample S;

    S.print();

    return 0;
}

Program 2:

#include <iostream>
using namespace std;

class Sample {
};

int main()
{
    Sample S;

    cout << sizeof(S);

    return 0;
}

Program 3:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        printf("%d", X);
    }
};

int main()
{
    Sample S;

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

    return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

main.cpp: In function ‘int main()’:
main.cpp:19:13: error: ‘void Sample::print()’ is protected within this context
     S.print();
             ^
main.cpp:9:10: note: declared protected here
     void print()
          ^~~~~

Explanation:

The above code will generate an error because, in the above program, we are trying to access the protected members outside the class. In C++, we can access protected members only in inheritance.

Answer Program 2:

Output:

1

Explanation:

In the above program, we created an empty class that did not contain any members of the class.

In C++, to distinguish the object of the class, that's why the size of the empty class is 1 byte.

In the main() function, we created an object of Sample class and print the size of the object that will be 1. Then the final output will be "1" printed on the console screen.

Answer Program 3:

Output:

10

Explanation:

Here, we created a class that contains data member X and two member functions set() and print().

In the print() function, we used printf() function, but here we did not include "stdio.h" header file. To use printf() here no need to include "stdio.h" explicitly, it is automatically included in most of the C++ compiler.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Class and Objects | Find output programs | Set... >>
<< C++ Class and Objects | Find output programs | Set...