Thursday, 5 December 2024

OOPS C++ Functions and Constructors MSBTE III Sem

Unit 2

Summer 2022

Q1. Define Constructor. List types of Constructors. (2 Marks)

Ans. A constructor is a special member function in a class that is automatically called when an object of the class is created. It is used to initialize the object's data members.

Characteristics of Constructors:

  1. The name of the constructor is the same as the class name.
  2. It has no return type, not even void.
  3. It is called automatically when an object is instantiated.

Types of Constructors in C++

  1. Default Constructor:
    • A constructor that takes no parameters.
    • Used to initialize objects with default values.

class Example {

    int x;

public:

    Example() { x = 0; } // Default constructor

};

  1. Parameterized Constructor:
    • A constructor that takes arguments to initialize an object with specific values.

class Example {

    int x;

public:

    Example(int val) { x = val; } // Parameterized constructor

};

  1. Copy Constructor:
    • A constructor that creates a new object as a copy of an existing object.

class Example {

    int x;

public:

    Example(const Example &obj) { x = obj.x; } // Copy constructor

};

  1. Dynamic Constructor:
    • A constructor that allocates memory dynamically for class members.

class Example {

    int *x;

public:

    Example() { x = new int(0); } // Dynamic constructor

};

  1. Delegating Constructor (C++11 and later):
    • A constructor that calls another constructor of the same class.

class Example {

    int x;

public:

    Example() : Example(0) {} // Delegating constructor

    Example(int val) { x = val; }

};

Q2. Write any two characteristics of friend functions. (2 Marks)

Ans.

  1. Access to Private and Protected Members:
    • A friend function has access to the private and protected members of the class it is a friend of, even though it is not a member of the class itself.
  2. Defined Outside the Class:
    • A friend function is declared inside the class with the keyword friend, but it is defined outside the class and does not have access to the this pointer of the class.

Example:

#include <iostream>

using namespace std;

class Example {

    int value;

public:

    Example(int val) : value(val) {}

    friend void display(const Example &obj); // Friend function declaration

};

// Friend function definition

void display(const Example &obj) {

    cout << "Value: " << obj.value << endl; // Accessing private member

}

int main() {

    Example e(42);

    display(e); // Calling the friend function

    return 0;

}

Q3. Write a C++ program to declare a class student with data members as rollno and name. Declare a constructor to initialize data members of class. Display the data. (4 Marks)

Ans.

#include <iostream>

#include <string>

using namespace std;

class Student {

    int rollno;

    string name;

public:

    // Constructor to initialize data members

    Student(int r, string n) {

        rollno = r;

        name = n;

    }

    // Function to display student details

    void display() {

        cout << "Roll Number: " << rollno << endl;

        cout << "Name: " << name << endl;

    }

};

int main() {

    // Create an object of Student and initialize data members

    Student s1(101, "John Doe");

    // Display the student details

    s1.display();

    return 0;

}

Sample Output:

Roll Number: 101
Name: John Doe

Q4. Describe constructor with default arguments with an example. (4 Marks)

Ans.

Constructor with Default Arguments

A constructor with default arguments allows you to assign default values to the parameters of the constructor. If the user does not provide arguments while creating an object, the constructor uses these default values.

Key Points:

  1. Default arguments are specified in the constructor's declaration.
  2. The constructor can be invoked with or without providing arguments.

Example

#include <iostream>

#include <string>

using namespace std;

class Student {

    int rollno;

    string name;

public:

    // Constructor with default arguments

    Student(int r = 0, string n = "Unknown") {

        rollno = r;

        name = n;

    }

    // Function to display student details

    void display() {

        cout << "Roll Number: " << rollno << endl;

        cout << "Name: " << name << endl;

    }

};

int main() {

    Student s1;              // Using default arguments

    Student s2(101);         // Providing one argument

    Student s3(102, "Alice"); // Providing both arguments

    cout << "Student 1:" << endl;

    s1.display();

    cout << "Student 2:" << endl;

    s2.display();

    cout << "Student 3:" << endl;

    s3.display();

    return 0;

}

Q5. Write a C++ program to declare two classes with data members as m1 and m2 respectively. Use friend function to calculate average of two (m1, m2) marks and display it.

Ans.

#include <iostream>

using namespace std;

class Class1; // Forward declaration

class Class2 {

    float m2; // Data member of Class2

public:

    Class2(float marks) : m2(marks) {} // Constructor to initialize m2

    friend float calculateAverage(Class1, Class2); // Friend function declaration

};

class Class1 {

    float m1; // Data member of Class1

public:

    Class1(float marks) : m1(marks) {} // Constructor to initialize m1

    friend float calculateAverage(Class1, Class2); // Friend function declaration

};


// Friend function to calculate the average of m1 and m2

float calculateAverage(Class1 obj1, Class2 obj2) {

    return (obj1.m1 + obj2.m2) / 2;

}

int main() {

    Class1 obj1(85.5); // Object of Class1 with marks 85.5

    Class2 obj2(90.0); // Object of Class2 with marks 90.0


    float avg = calculateAverage(obj1, obj2); // Calculate average using the friend function

    cout << "The average of m1 and m2 is: " << avg << endl; // Display the average

    return 0;

}

Sample Output:

The average of m1 and m2 is: 87.75

Q6. Write two characteristics of static data member. Write C++ program to count number of objects created with the help of static data member. (4 Marks)

Ans.

Characteristics of Static Data Members:

  1. Shared Among All Objects:
    • A static data member is shared by all objects of a class. There is only one copy of the static data member, and it is common to all objects.
  2. Class-Level Scope:
    • Static data members are associated with the class rather than any specific object. They are declared inside the class but must be defined outside the class.

Q7. C++ Program to Count Number of Objects Created:

This program demonstrates how to use a static data member to count the number of objects created for a class.

#include <iostream>

using namespace std;

class Counter {

    static int objectCount; // Static data member declaration

public:

    // Constructor increments the object count

    Counter() {

        objectCount++;

    }

    // Static member function to get the object count

    static int getObjectCount() {

        return objectCount;

    }

};

// Define and initialize static data member outside the class

int Counter::objectCount = 0;

int main() {

    Counter obj1; // First object created

    Counter obj2; // Second object created

    Counter obj3; // Third object created

    // Display the total number of objects created

    cout << "Number of objects created: " << Counter::getObjectCount() << endl;

    return 0;

}

Sample Output:

Number of objects created: 3


Winter 2022

Q8. Explain with suitable example Friend Function.

Ans.

Friend Function in C++

A friend function is a special function that is not a member of a class but can access the private and protected members of the class. It is declared using the keyword friend in the class definition.

Key Points:

  1. A friend function is not called using an object of the class; it is invoked like a normal function.
  2. It has access to private and protected members of the class where it is declared as a friend.
  3. A single friend function can be a friend to multiple classes.

Example: Calculating the Sum of Private Members

#include <iostream>

using namespace std;

class Class1 {

    int num1; // Private member of Class1

public:

    // Constructor to initialize num1

    Class1(int x) : num1(x) {}

 

    // Declare friend function

    friend int calculateSum(Class1, Class2);

};

class Class2 {

    int num2; // Private member of Class2

public:

    // Constructor to initialize num2

    Class2(int y) : num2(y) {}

    // Declare friend function

    friend int calculateSum(Class1, Class2);

};

// Friend function definition

int calculateSum(Class1 obj1, Class2 obj2) {

    return obj1.num1 + obj2.num2; // Access private members of both classes

}

int main() {

    Class1 obj1(10); // Object of Class1 with num1 = 10

    Class2 obj2(20); // Object of Class2 with num2 = 20

    // Call friend function to calculate the sum

    cout << "Sum of num1 and num2: " << calculateSum(obj1, obj2) << endl;

    return 0;

}

Q9. Develop a C++ program to print sum of 10 nos, using array.

Ans.

#include <iostream>

#include <conio.h> 

using namespace std;

void main() {

    int arr[20], i, n, sum = 0;

    // Input size of the array

    cout << "\nEnter size of an array: ";

    cin >> n;

    // Input validation

    if (n > 20 || n <= 0) {

        cout << "\nInvalid size! Size should be between 1 and 20.";

        return;

    }

    // Input array elements

    cout << "\nEnter the elements of the array: ";

    for (i = 0; i < n; i++) {

        cin >> arr[i];

    }

    // Calculate the sum of the array elements

    for (i = 0; i < n; i++)

   {

        sum = sum + arr[i];

    }

    // Display the sum

    cout << "\nSum of array elements is: " << sum;

    getch(); // Wait for key press (if applicable)

}

Q9. Define class book with following data member and member functions for 10 book: (4 Marks)

Data members

Member function

B-name

 

getdata()

 

B-author

 

getdata()

 

B-price

 

putdata()

 

Ans.

#include <iostream>

#include <string>

using namespace std;

class Book {

    string B_name;   // Book name

    string B_author; // Book author

    float B_price;   // Book price

public:

    // Function to get data for a book

    void getdata() {

        cout << "Enter Book Name: ";

        cin.ignore(); // To handle newline character

        getline(cin, B_name);

        cout << "Enter Author Name: ";

        getline(cin, B_author);

        cout << "Enter Book Price: ";

        cin >> B_price;

    }

    // Function to display data for a book

    void putdata() const {

        cout << "Book Name: " << B_name << endl;

        cout << "Author: " << B_author << endl;

        cout << "Price: $" << B_price << endl;

    }

};

int main() {

    Book books[10]; // Array to store data for 10 books

    // Input data for 10 books

    cout << "Enter details of 10 books:\n";

    for (int i = 0; i < 10; i++) {

        cout << "\nBook " << i + 1 << ":\n";

        books[i].getdata();

    }

    // Display data for 10 books

    cout << "\nDetails of the books:\n";

    for (int i = 0; i < 10; i++) {

        cout << "\nBook " << i + 1 << ":\n";

        books[i].putdata();

    }

    return 0;

}

Q10. Compare static and non-natic data members (any four points

Ans. Following table compares static and non-static data members

 

Static Data Member

Non-static Data Member

1

Memory Allocation: Static data members are allocated memory only once, shared among all objects of the class. There is only one copy of the static data member, no matter how many objects are created from the class.

 

Non-static data members are allocated memory separately for each object of the class. Each object gets its own copy of these members.

2

Static Data Members: Static data members can be accessed using the class name (e.g., ClassName::dataMember) or through objects. They do not require an object to access them.

Non-static data members must be accessed through an object of the class. They cannot be accessed directly using the class name.

3

Initialization: Static data members need to be defined outside the class, even though they are declared inside. They are initialized once, and their value is shared across all objects.

Non-static data members are initialized separately for each object. Their values can be different for each object.

4

Scope and Lifetime: The scope of a static data member is limited to the class, but its lifetime extends for the duration of the program. It persists across function calls and object destructions.

The scope of non-static data members is specific to the object they belong to, and their lifetime is tied to the object's lifetime. Once the object is destroyed, the memory for these members is freed.

5

Declaration Syntax:

static data type variable;

e.g. static int count;

Declaration Syntax:

static data type variable;

eg. int nonStaticVar;

 

Q11. Write a program to show object as function argument.

Ans.

#include <iostream>

using namespace std;

class Rectangle {

    int length, breadth;

public:

    // Constructor to initialize the rectangle dimensions

    Rectangle(int l, int b) : length(l), breadth(b) {}

    // Member function to display the dimensions of the rectangle

    void display() const {

        cout << "Length: " << length << ", Breadth: " << breadth << endl;

    }

    // Member function to calculate the area of the rectangle

    int area() const {

        return length * breadth;

    }

};


// Function to calculate the area by taking the object as an argument

void calculateArea(Rectangle& rect) {

    cout << "Area of the rectangle: " << rect.area() << endl;

}


int main() {

    // Create an object of Rectangle

    Rectangle rect1(10, 5);

    // Display the dimensions of the rectangle

    rect1.display();

    // Pass the object to the function to calculate the area

    calculateArea(rect1);

    return 0;

}

Sample Output:

Length: 10, Breadth: 5
Area of the rectangle: 50

Q12. State the difference between constructor and destructor (any six points).

Ans.

1. Purpose:

  • Constructor:
    • A constructor is used to initialize an object when it is created. It sets the initial state of the object.
  • Destructor:
    • A destructor is used to clean up or release resources (like memory or file handles) when an object goes out of scope or is destroyed.

2. Syntax:

  • Constructor:
    • A constructor has the same name as the class and does not have a return type (not even void).

class MyClass {

    MyClass() {

        // Constructor code

    }

};

  • Destructor:
    • A destructor has the same name as the class, preceded by a tilde (~), and it does not return any value.

class MyClass {

    ~MyClass() {

        // Destructor code

    }

};

3. Invocation:

  • Constructor:
    • A constructor is called automatically when an object is created.
  • Destructor:
    • A destructor is called automatically when an object is destroyed or goes out of scope.

4. Parameters:

  • Constructor:
    • Constructors can have parameters, which allow initialization of objects with specific values.

MyClass(int x) { /* constructor code */ }

  • Destructor:
    • Destructors cannot have parameters. They do not accept any arguments.

~MyClass() { /* destructor code */ }

5. Overloading:

  • Constructor:
    • Constructors can be overloaded, meaning you can have multiple constructors with different parameters in the same class.
  • Destructor:
    • Destructors cannot be overloaded. A class can have only one destructor.

6. Automatic Call:

  • Constructor:
    • The constructor is called only once when the object is created, either on the stack or heap.
  • Destructor:
    • The destructor is called once when the object goes out of scope or is explicitly deleted (in case of dynamically allocated memory).

Summary of Differences:

Aspect

Constructor

Destructor

Purpose

Initializes an object when it is created.

Cleans up or releases resources when the object is destroyed.

Name

Same as the class name.

Same as the class name but with a ~ prefix.

Return Type

No return type.

No return type.

Parameters

Can have parameters.

Cannot have parameters.

Overloading

Constructors can be overloaded.

Destructors cannot be overloaded.

Invocation

Automatically called when an object is created.

Automatically called when an object is destroyed or goes out of scope.


Q13. Explain inline member function. (2 Marks)

Ans.

An inline member function in C++ is a function defined inside the class definition. It suggests the compiler to replace the function call with the actual function code during compilation, eliminating the overhead of a function call. Inline functions are best suited for small and frequently used functions.

#include <iostream>

using namespace std;

class Rectangle

{

    int length, breadth;

    public:

    Rectangle(int l, int b) : length(l), breadth(b) {}

    // Inline member function

    int area()

   {

        return length * breadth;

    }

};

int main()

{

    Rectangle rect(10, 5);

    cout << "Area: " << rect.area() << endl; // Inline function call

    return 0;

}

Advantages:

  1. Eliminates function call overhead.
  2. Improves execution speed for small functions.

Winter 2023

Q14. Write a program to declare a class measure having data members add1, add2, add3. Initialize the data members using constructor and store their addition in third data member using function and display the addition.

Ans.

//Using Parameterized Constructor

#include <iostream>

using namespace std;

class Measure

{

    int add1, add2, add3;

public:

    // Parameterized constructor

    Measure(int a, int b)

  {

        add1 = a;

        add2 = b;

        add3 = 0; // Initialize add3 to 0

    }

    // Function to calculate sum

    void sum() {

        add3 = add1 + add2;

    }

    // Function to display the result

    void display() {

        cout << "Sum: " << add3 << endl;

    }

};

int main() {

    Measure m(10, 20); // Parameterized constructor is called

    m.sum();           // Calculate sum

    m.display();       // Display result

    return 0;

}

Q15. Differentiate between constructor and destructor in C++. (Any four points).

Ans.

1. Purpose:

  • Constructor:
    • Used to initialize objects when they are created.
  • Destructor:
    • Used to clean up resources or perform cleanup tasks when objects are destroyed.

2. Syntax:

  • Constructor:
    • Has the same name as the class and no return type.

class MyClass {

    MyClass() { /* constructor code */ }

};

  • Destructor:
    • Has the same name as the class, preceded by a tilde (~), and no return type.

class MyClass {

    ~MyClass() { /* destructor code */ }

};

3. Invocation:

  • Constructor:
    • Called automatically when an object is created.
  • Destructor:
    • Called automatically when an object goes out of scope or is explicitly deleted.

4. Parameters:

  • Constructor:
    • Can have parameters to initialize objects with specific values (overloading is allowed).
  • Destructor:
    • Cannot have parameters (no overloading allowed).

Q16. Write a program to declare a class 'employee' containing data members 'emp-id" and "salary” Accept and display this data for 10 employees.

Ans.

#include <iostream>

using namespace std;

class Employee {

private:

    int emp_id;

    double salary;

public:

    // Member function to set data

    void setData(int id, double sal) {

        emp_id = id;

        salary = sal;

    }

    // Member function to display data

    void displayData() {

        cout << "Employee ID: " << emp_id << ", Salary: " << salary << endl;

    }

};

int main() {

    Employee employees[10]; // Array to store 10 Employee objects

    // Accepting data for 10 employees

    for (int i = 0; i < 10; i++) {

        int empId;

        double salary;

        cout << "Enter details for Employee " << i + 1 << ":" << endl;

        cout << "Enter Employee ID: ";

        cin >> empId;

        cout << "Enter Salary: ";

        cin >> salary;


        employees[i].setData(empId, salary);

    }

    // Displaying data for 10 employees

    cout << "\nDetails of Employees:\n";

    for (int i = 0; i < 10; i++) {

        cout << "Employee " << i + 1 << ": ";

        employees[i].displayData();

    }

    return 0;

}

Summer 2024

Q17. Develop a C++ program to create structure book with data members name, cost and author. Accept and display data for 5 books using structure.

Ans.

#include <iostream>

#include <string>

using namespace std;

struct Book {

    char name[30];

    int cost;

    char author[30];

};

int main() {

    Book b[5]; // Array of 5 books

    int i;

    // Input details for 5 books

    for (i = 0; i < 5; i++) {

        cout << "\nEnter the details for Book " << i + 1 << ":" << endl;

        cout << "Enter Book Name: ";

        cin.ignore(); // To clear the buffer for getline

        cin.getline(b[i].name, 30);

        cout << "Enter Book Cost: ";

        cin >> b[i].cost;

        cin.ignore(); // To clear the buffer for getline

        cout << "Enter Author Name: ";

        cin.getline(b[i].author, 30);

    }

    // Display the details of 5 books

    cout << "\nBook Information:\n";

    for (i = 0; i < 5; i++) {

        cout << "\nBook " << i + 1 << " Details:" << endl;

        cout << "Name: " << b[i].name << endl;

        cout << "Cost: " << b[i].cost << endl;

        cout << "Author: " << b[i].author << endl;

    }

 

    return 0;

}

Q4. Develop a C++ program using parameterized constructor.

Ans.

#include <iostream>

using namespace std;

class Rectangle {

private:

    int length;

    int breadth;

public:

    // Parameterized Constructor

    Rectangle(int l, int b) {

        length = l;

        breadth = b;

    }

    // Member function to calculate area

    int area() {

        return length * breadth;

    }

    // Member function to display dimensions

    void display() {

        cout << "Length: " << length << ", Breadth: " << breadth << endl;

    }

};

int main() {

    // Creating objects using the parameterized constructor

    Rectangle rect1(10, 5);

    Rectangle rect2(7, 3);


    // Display details and area of rect1

    cout << "Rectangle 1:" << endl;

    rect1.display();

    cout << "Area: " << rect1.area() << endl;

    // Display details and area of rect2

    cout << "\nRectangle 2:" << endl;

    rect2.display();

    cout << "Area: " << rect2.area() << endl;

    return 0;

}

No comments:

Post a Comment

Summer 2018 Programming in C Solved Question Paper

Summer 2018 Semester II – C Programming   Q1. Attempt any FIVE of the following : 10 (a) Define : (i) Two dimensional array In C...