Classes and Objects Q/A

Q/A C++  Classes and Objects

1. Define class. What is the difference between structures and classes in C++?
Ans. 

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −

class Box {
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected .


1) Structure :- In structure have a by default public. In class have a by default private.
2) Structure cannot be inherited. But class can be inherit.
3) There is no data hiding features comes with structures. Classes do, private, protected and public.
4) A structure can't be abstract, a class can. 5) A structure is a value type, while a class is a reference type.
6) A structure is contain only data member , but class contain data member and member function.
7) In a Structure we can't initilse the value to the variable but in class variable we assign the values.
8) Structure are value type, They are stored as a stack on memory. where as class are reference type. They are stored as heap on memory.

2. How can you pass an object of a C++ class to/from a C function?
Ans. 

Passing object of a class to a function
Syntax:
function_name(object_name)


In C++ we can pass class’s objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.

Passing an Object as argument

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.
Syntax:
function_name(object_name);

Example: In this Example there is a class which has an integer variable ‘a’ and a function ‘add’ which takes an object as argument. The function is called by one object and takes another as an argument. Inside the function, the integer value of the argument object is added to that on which the ‘add’ function is called. In this method, we can pass objects as an argument and alter them.
// C++ program to show passing 
// of objects to a function 

#include <bits/stdc++.h> 
using namespace std; 

class Example { 
public: 
int a; 

// This function will take 
// an object as an argument 
void add(Example E) 

a = a + E.a; 

}; 

// Driver Code 
int main() 


// Create objects 
Example E1, E2; 

// Values are initialized for both objects 
E1.a = 50; 
E2.a = 100; 

cout << "Initial Values \n"; 
cout << "Value of object 1: " << E1.a 
<< "\n& object 2: " << E2.a 
<< "\n\n"; 

// Passing object as an argument 
// to function add() 
E2.add(E1); 

// Changed values after passing 
// object as argument 
cout << "New values \n"; 
cout << "Value of object 1: " << E1.a 
<< "\n& object 2: " << E2.a 
<< "\n\n"; 

return 0; 


Output:
Initial Values 
Value of object 1: 50
& object 2: 100

New values 
Value of object 1: 50
& object 2: 150
Returning Object as argument
Syntax:

object = return object_name;
Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type ‘Example'(i.e., class name) whose value is stored in E3.

In this example, we can see both the things that are how we can pass the objects as well as return them. When the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2 and value of E3 by object3.
// C++ program to show passing 
// of objects to a function 

#include <bits/stdc++.h> 
using namespace std; 

class Example { 
public: 
int a; 

// This function will take 
// object as arguments and 
// return object 
Example add(Example Ea, Example Eb) 

Example Ec; 
Ec.a = Ec.a + Ea.a + Eb.a; 

// returning the object 
return Ec; 

}; 
int main() 

Example E1, E2, E3; 

// Values are initialized 
// for both objects 
E1.a = 50; 
E2.a = 100; 
E3.a = 0; 

cout << "Initial Values \n"; 
cout << "Value of object 1: " << E1.a 
<< ", \nobject 2: " << E2.a 
<< ", \nobject 3: " << E3.a 
<< "\n"; 

// Passing object as an argument 
// to function add() 
E3 = E3.add(E1, E2); 

// Changed values after 
// passing object as an argument 
cout << "New values \n"; 
cout << "Value of object 1: " << E1.a 
<< ", \nobject 2: " << E2.a 
<< ", \nobject 3: " << E3.a 
<< "\n"; 

return 0; 


Output:
Initial Values 
Value of object 1: 50, 
object 2: 100, 
object 3: 0

New values 
Value of object 1: 50, 
object 2: 100, 
object 3: 200

3. Can a method directly access the non-public members of another instance of its class?


Ans. Yes.The name this is not special. Access is granted or denied based on the class of the reference/pointer/object, not based on the name of the reference/pointer/object. 

The fact that C++ allows a class' methods and friends to access the non-public parts of all its objects, not just the this object, seems at first to weaken encapsulation. However the opposite is true: this rule preserves encapsulation. Here's why.


Without this rule, most non-public members would need a public get method, because many classes have at least one method or friend that takes an explicit argument (i.e., an argument not called this) of its own class.

4. What’s the difference between the keywords struct and class?

Ans. The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.


 A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

5. Write a program to add two numbers defining a member getdata () and display () inside a class named sum and displaying the result.

Ans. 
#include<iostream.h>
#include<conio.h>
Class sum
{
Int A, B, Total;
Public:
Void getdata ();
Void display ();
};
Void sum:: getdata ()
{
Cout<<” \n enter the value of A and B”;
Cin>>A>>B;
}
Void sum:: display ()
{
Total =A+B;
Cout<<”\n the sum of A and B=”<<Total;
}
Void main ()
{
Sum a;
a.getdata ();
a.display ();
getch ();

}

6. How does C++ help with the tradeoff of safety vs. usability?
Ans.
In C, encapsulation was accomplished by making things static in a compilation unit or module. This prevented another module from accessing the static stuff. (By the way, static data at file-scope is now deprecated in C++: don’t do that.)

Unfortunately this approach doesn’t support multiple instances of the data, since there is no direct support for making multiple instances of a module’s static data. If multiple instances were needed in C, programmers typically used a struct. But unfortunately C structs don’t support encapsulation. This exacerbates the tradeoff between safety (information hiding) and usability (multiple instances).

In C++, you can have both multiple instances and encapsulation via a class. The public part of a class contains the class’s interface, which normally consists of the class’s public member functions and its friend functions. The private and/or protected parts of a class contain the class’s implementation, which is typically where the data lives.


The end result is like an “encapsulated struct.” This reduces the tradeoff between safety (information hiding) and usability (multiple instances).

7. “The main advantage of using a static member is to declare the global data which should be updated while the program lives in memory”. Justify your statement.

Ans.
Static data members are data objects that are common to all objects of a class. Static data members exist only once in all objects of one class. The static members are used when the information is to be shared. They can be public or private data. The main advantage of using a static member is to declare the global data which should be updated while the program lives in memory.
When a static member is declared private, the non member functions cannot access these members. But a public static member can be accessed by any member of the class. The static data member should be created and initialized before the main function control block begins.

Consider the following program which demonstrates the use of static data members count. The variable count is declared static in the class but initialized to 0 outside the class.

#include <iostream>
using namespace std;
class Counter
{
static int count;
public :
void disp()
{
count++;
cout << "The present value of count is : " << count << "\n";
}
};
int Counter :: count = 0;
int main ()
{
Counter counterobj;
for(int i = 0; i < 5; i++)
{
counterobj.disp();
}
return 0;

}

Following are some interesting facts about static variables in C.

1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.
2) Static variables are allocated memory in data segment, not stack segment. See memory layout of C programs for details.
3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.
4) In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.
5) Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope of a variable or function to a file. Please refer Static functions in C for more details.
6) Static variables should not be declared inside structure. The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous.

8. Write a program to print the score board of a cricket match in real time. The display should contain the batsman’s name, runs scored, indication if out, mode by which out, bowler’s score (overs played, maiden overs, runs given, wickets taken). As and when a ball is thrown, the score should be updated. (print: Use separate arrays to store batsmen’s and bowler’s information).

Ans.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct bat
{
char name[20],modeout[70], indica;
int runs, score, totruns, totove, xtras;
};

struct bowl
{
char name[20];
int ttvrs,rnsgvn,wktstkn;
};
void main()
{
clrscr();
int plno;
int plytyp;
bat pl1[3];
bowl pl2[3];



cout<<"Enter the batsmen details:"<<endl;
for (int i=0;i<3;i++)
{
cout<<"Enter name of player "<<i+1<<endl;
gets (pl1[i].name);
cout<<"enter the runs scored by player "<<i+1<<endl;
cin>>pl1[i].runs;
cout<<"Enter the overs played by the player"<<i+1<<endl;
cin>>pl1[i].totove;
cout<<"Enter the status of the player if out (N)or not(Y)"<<endl;
cin>>pl1[i].indica;
}



cout<<"Enter the bowlers details "<<endl;
for (i=0;i<3;i++)
{
cout<<"Enter the name of the bowler "<<i+1<<endl;
gets(pl2[i].name);
cout<<"Enter the runs given by the bowler "<<i+1<<endl;
cin>>pl2[i].rnsgvn;
cout<<"Enter the wickets taken by the bowler "<<i+1<<endl;
cin>>pl2[i].wktstkn;
cout<<"Enter the total overs played by the  bowler "<<i+1<<endl;
cin>>pl2[i].ttvrs;
}


cout<<"Thank you all details recd"<<endl;
xyz:
cout<<"Select between batsmen(1) or bowlers(2) to see their details"<<endl;
abc:
cin>>plytyp;


switch (plytyp)
{


case 1:
cout<<"Enter the batsman number to see his details "<<endl<<endl<<endl;
cin>>plno;
plno--;
cout<<"Batsman number :"<<plno+1<<endl;
cout<<"Batsman name :";
puts(pl1[plno].name);
cout<<"Runs scored by the batsman :"<<pl1[plno].runs<<endl;
cout<<"Total overs played by the batsman :"<<pl1[plno].totove<<endl;
cout<<"Player status out "<<pl1[plno].indica<<endl;
break;



case 2:
cout<<"Enter the bowlers number to see his details "<<endl<<endl<<endl;
cin>>plno;
plno--;
cout<<"Bowlers name :";
puts(pl2[plno].name);
cout<<"Runs given by the player is :"<<pl2[plno].rnsgvn<<endl;
cout<<"Total overs played by the player :"<<pl2[plno].ttvrs<<endl;
cout<<"Total wickets taken by the user :"<<pl2[plno].wktstkn<<endl;
break;


default:
cout<<"Idiot enter a decent value"<<endl;
goto abc;
}

cout<<endl<<endl<<endl<<"Do you wish to continue? Y-1 N-2"<<endl;
cin>>plno;
if (plno==1)
goto xyz;
else
cout<<"Thank you Press any key to exit";
getch();
}

output:
  Enter the batsmen details:
Enter name of player 1
SACHIN
enter the runs scored by player 1
34
Enter the overs played by the player1
6
Enter the status of the player if out (N)or not(Y)
N
Enter name of player 2
GAMBHIR
enter the runs scored by player 2
12
Enter the overs played by the player2
5
Enter the status of the player if out (N)or not(Y)
Y
Enter name of player 3
SEHWAG
enter the runs scored by player 3
56
Enter the overs played by the player3
11
Enter the status of the player if out (N)or not(Y)
N
Enter the bowlers details
Enter the name of the bowler 1
31
Enter the wickets taken by the bowler 1
1
Enter the total overs played by the  bowler 1
5
Enter the name of the bowler 2
JOHNSON
Enter the runs given by the bowler 2
25
Enter the wickets taken by the bowler 2
0
Enter the total overs played by the  bowler 2
4
Enter the name of the bowler 3
MCGRATH
Enter the runs given by the bowler 3
40
Enter the wickets taken by the bowler 3
0
Enter the total overs played by the  bowler 3
7
Thank you all details recd
Select between batsmen(1) or bowlers(2) to see their details
2
Enter the bowlers number to see his details


2
Bowlers name :JOHNSON
Runs given by the player is :25
Total overs played by the player :4
Total wickets taken by the user :0



Do you wish to continue? Y-1 N-2
Y
Select between batsmen(1) or bowlers(2) to see their details
Enter the bowlers number to see his details


Bowlers name :LEE
Runs given by the player is :31
Total overs played by the player :5
Total wickets taken by the user :1

                                                                               
Do you wish to continue? Y-1 N-2                                               

Thank you Press any key to exit            


9. If a member of a class is public, it can be accessed by an external function including a derived class. Explain with an example.

Ans.

A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −

class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.


Consider a base class Shape and its derived class Rectangle as follows −
#include <iostream>
 
using namespace std;

// Base class
class Shape {
   public:
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
      
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape {
   public:
      int getArea() { 
         return (width * height); 
      }
};

int main(void) {
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
10. Write a program in which a class has one private member (properties) and two public member (method).
Ans.


#include <iostream>
using namespace std;

//class definition
class Numbers
{
 private:
  int a;
  int b;
 public:
  //member function declaration
  void readNumbers(void);
  void printNumbers(void);
  int calAddition(void);
};

//member function definitions
void Numbers::readNumbers(void)
{
 cout<<"Enter first number: ";
 cin>>a;
 cout<<"Enter second number: ";
 cin>>b; 
}

void Numbers::printNumbers(void)
{
 cout<<"a= "<<a<<",b= "<<b<<endl;
}

int Numbers::calAddition(void)
{
 return (a+b);
}

//main function
int main()
{
 //declaring object
 Numbers num;
 int add; //variable to store addition
 //take input
 num.readNumbers();
 //find addition
 add=num.calAddition();
 
 //print numbers
 num.printNumbers();
 //print addition
 cout<<"Addition/sum= "<<add<<endl;
 
 return 0; 
}
Output
Enter first number: 100 
Enter second number: 200
a= 100,b= 200 
Addition/sum= 300

Comments