This section contains the C++ find output programs with their explanations on C++ Class and Objects (set 1).
Program 1:
#include <iostream>
using namespace std;
class Sample {
private
int A;
private
int B;
public
void init()
{
A = 10;
B = 20;
}
public
void print()
{
cout << A << " " << B;
}
};
int main()
{
Sample S;
S.init();
S.print();
return 0;
}
Program 2:
#include <iostream>
using namespace std;
class Sample {
private:
int A;
int B;
public:
private:
public:
void init()
{
A = 10;
B = 20;
}
void print()
{
cout << A << " " << B;
}
};
int main()
{
Sample S;
S.init();
S.print();
return 0;
}
Program 3:
#include <iostream>
using namespace std;
class Sample {
int A = 10;
int B = 20;
public:
void print()
{
cout << A << " " << B;
}
};
int main()
{
Sample S;
S.print();
return 0;
}
Answer Program 1:
Output:
Explanation:
The above code will generate errors because in the above program we did not use private and public modifiers properly.
In C++, we need to use the colon ":" operator to specify modifiers block. Here we did not use modifiers for each member individually, here we create blocks like,
Here A and B are private members and fun() is public in ABC class.
Answer Program 2:
Output:
Explanation:
In the above program, we created a class Sample. Here we created two private members A and B. After that we used modifiers multiple times, In C++, last used modifiers decide the visibility of members so init() and print() function will be public type.
Now, come to main() function, here we created of the object of Sample class and call init() and print() function then the "10 20" will be printed on the console screen.
Answer Program 3:
Output:
Explanation:
In the above program, we created a Sample class that contains two data member A and B, they initialized with 10 and 20 respectively. Here we initial member at the time of declaration. It is also possible in C++.
Here we did not mention any access modifier. In C++, if we did not any specify any modifier then by default it will be considered as a private type.
In the main() function, we create object S of Sample class and then call print() member function of Sample class, which will print "10 20" on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer