If Else

Classes and Objects

1. What is the diffrence between local variables and instance variables.
Answer: Local Variables are declared within Method body and used within that method only. but Instance variables are declared within class and outside the methods, and can be used in any method within that class.

2. Is there any diffrence between Instance and Object.
Answer: No

3. Are Class variables and Instance variables same thing.
Answer: Yes

4.//read the program and write Answers:
class Product
{
    int Price,Qty,total;
    public:
    void setDate(int P,int Q)
    {
        Price=P;
        Qty=Q;
    }
    void doTotal()
    {
        total=Price*Qty;
        float Discount=total*10/100;
        cout<<Discount;
    }
    void show()
    {
        cout<<"Net="<<total-Discount;
    }
};
int main()
{
    Product p;
    p.setData(100,20);
    p.doTotal();
    p.show();
}
Q 4.1  Identify Instance Variable.
Answer: Price, Qty, total

Q 4.2  Identify local variables in class
Answer: P, Q, Discount

Q 4.3  Is there any error in doTotal() method
Answer: No

Q 4.4  Is there any error in show() method if yes what??
Answer: Discount is a local variable of doTotal() method, so it cannot be used in show() method.

Q 4.5  Is there any instance of class?
Answer: Yes, p is a instance of class.

Q 4.6  Why the value of P is assigned to Price in setData() Method?
Answer: So, that given Price can be used in all other methods.

Q 4.7  What happen if we remove public: from class?
Answer: Methods become private and private methods can not be accessed from main().

Q 4.8  How to Make instance variables public?
Answer: By declared them with public specifier.

Q 4.9  Why we keep Instance variables Private?
Answer: So that any outside method from class like main() can not directly access the members of class.

//what will be the output:
5. class A
{
    public:
    int x;
};
main()
{
    A obj;
    cout<<obj.x;
}
Answer: Garbage Value

6. output/error
class B
{
    public:
    int y=10;
};
main()
{
B obj2;
cout<<obj2.y;
}
Answer: 10

7. Find error and Write it Correctly
class Pen()
{
    int Qty;
    float Price;
    public;
    void getData(int Q,P)
    {
        Q=Qty;
        P=Price;
    }
    void process()
    {
        cout<<"total=",Q*P;
    };
    int main()
    {
        Pen p;
        p.setData(10,5);
        p.process();
    }
};
Answer:
class Pen
{
int Qty;
float Price;
public:
void setData(int Q,float P)
{
Qty=Q;
Price=P;
}
void process()
{
cout<<"total="<<Qty*Price;
}
};
int main()
{
Pen p;
p.setData(10,5);
p.process();
}

Confirm your Answer