C
C
C
In C++, there are primarily three ways to define member functions of a class:
When a member function is defined inside the class definition, it is automatically treated as
an inline function. Inline functions are those where the compiler attempts to expand the
function's code at the point of call, rather than generating a typical function call.
Member functions can be defined outside the class definition. This is commonly used when
the function implementations are large or need to be separated for better readability and
organization. The function declaration is within the class, but the definition is outside.
Example:
3. Using the Scope Resolution Operator
The scope resolution operator :: is used in the definition of member functions outside the
class to specify which class the member function belongs to. This operator helps in resolving
the scope of the function to the class it is part of.
The scope resolution operator is crucial in defining member functions outside the class. It
ensures that the compiler understands that the function being defined belongs to a specific
class. This operator helps in associating the function definition with its corresponding class
declaration.
Example:
In this example, MyClass:: before myFunction tells the compiler that myFunction is a
member of MyClass. Without the scope resolution operator, the compiler would not be able
to associate the function definition with the correct class, leading to errors.
Summary
• Inline Definition: Member functions defined inside the class definition are treated as
inline functions.
• Outside Definition: Member functions can be defined outside the class definition
using the scope resolution operator.
• Scope Resolution Operator (::): Used to specify the class to which the member
function belongs when defining the function outside the class. This operator is
essential for correctly associating the function definition with its class declaration.
2. Explain in detail about the significance of static data and member functions in C++?
In C++, the use of static data members and static member functions is a powerful feature that
provides class-level data and functionality. Let's dive into the details and significance of these
static members:
Static data members (also known as class variables) are variables that are shared among all
objects of a class. Unlike instance variables, which have a separate copy for each object, a
static data member has only one copy that is shared by all instances of the class.
Key Points:
Shared Data: Static data members are shared across all instances of the class. This means
that if one object modifies the static data member, the change is reflected across all other
objects of that class.
Class Scope: Static data members exist at the class level, not at the object level. They are
declared using the static keyword inside the class definition but need to be defined outside the
class, usually in the implementation file.
Initialization: Static data members must be explicitly defined and initialized outside the class
definition. This is because they are not tied to any instance and need a single point of
initialization.
Lifetime: The lifetime of a static data member is the entire duration of the program. It is
created when the program starts and destroyed when the program ends.
Access: They can be accessed using the class name and the scope resolution operator (::),
without needing to instantiate an object of the class.
Example:
class MyClass {
public:
static int counter;
MyClass() {
counter++;
}
};
int main() {
MyClass obj1;
MyClass obj2;
MyClass obj3;
std::cout << "Counter: " << MyClass::counter << std::endl; // Outputs: Counter: 3
return 0;
}
Key Points:
Class Scope: Like static data members, static member functions are associated with the class, not
with any specific object. They are declared with the static keyword inside the class definition.
No this Pointer: Static member functions do not have access to the this pointer, because they are
not called on a particular instance of the class. Hence, they can only access other static data
members or static member functions.
Utility Functions: They are often used to create utility functions that perform operations related to
the class but do not require access to instance-specific data.
Access: Static member functions can be called using the class name and the scope resolution
operator (::), just like static data members.
Example:
class MyClass {
public:
static int counter;
MyClass() {
counter++;
}
int main() {
MyClass obj1;
MyClass obj2;
MyClass obj3;
• Resource Sharing: Static data members are ideal for data that needs to be shared among all
instances of a class. For example, they can be used for counting the number of objects
created, managing connection pools, or caching data that is expensive to compute.
• Global Access: Static member functions and data members provide a way to encapsulate
and manage global data within the class. This helps in maintaining modularity and
encapsulation.
• Utility and Helper Functions: Static member functions are useful for creating utility functions
that operate on class-level data or perform operations that don't require any object-specific
information. This makes the code more organized and logically grouped within the relevant
class.
• Efficiency: Accessing static members can be more efficient in certain cases because they
avoid the overhead of creating and managing instances when not necessary.
In conclusion, static data members and static member functions in C++ offer powerful capabilities
for managing shared data and class-level operations, promoting better organization, efficiency, and
modularity in your code.
3. Explain the concept of default constructor,copy constructor and parameterized constructor with
the help of suitable c++ program.
Constructors in C++
A constructor is a special member function that is automatically called when an object of a class is
created. Constructors are primarily used to initialize objects. They have the same name as the class
and do not have a return type.
Types of Constructors
• Default Constructor: A constructor that takes no arguments.
• Parameterized Constructor: A constructor that takes one or more arguments.
• Copy Constructor: A constructor that initializes an object using another object of the same
class.
•
1. Default Constructor
A default constructor is one that can be called with no arguments. If no constructors are explicitly
defined in a class, the C++ compiler provides a default constructor. This constructor initializes
member variables to default values (like zero for fundamental types).
Syntax:
Explanation:
2. Parameterized Constructor
A parameterized constructor is one that takes arguments. It allows for initializing objects with
specific values when they are created. This is useful for providing custom initialization values for the
object's attributes.
Syntax:
Example Program:
Explanation:
3. Copy Constructor
A copy constructor is a constructor that initializes a new object as a copy of an existing object. It is
called when a new object is created from an existing object, either through direct initialization or
through passing objects to functions by value.
Syntax:
Example Program:
Explanation:
Summary
4. Describe a Friend function and how it can be used with programming examples.
Friend functions are useful when you need to allow an external function to access the private data of
a class without making those data members public. This can help in maintaining encapsulation while
still allowing necessary access for certain operations.
Syntax:
Programming Examples
Example 1: Simple Friend Function
Explanation:
• Class Box: Contains a private member width.
• Friend Function setWidth: Defined outside the class but declared as a friend within the class,
allowing it to access the private member width.
• Function Call: setWidth(box, 10.5) sets the width of box to 10.5 using the friend function.
•
Output:
Classes ClassA and ClassB: Each class has a private member (a in ClassA and b in ClassB).
Friend Function add: Declared as a friend in both classes, allowing it to access their private members.
Function Call: add(objA, objB) returns the sum of the private members a and b of objects objA and
objB, respectively.
Output:
When to Use Friend Functions
• When you need to allow an external function to access private or protected members of a
class.
• When you want to maintain encapsulation but still need to perform operations that require
access to the internals of a class.
• When you need to perform operations involving private members of multiple classes.
Summary
Friend functions in C++ are a way to provide external functions access to a class's private and
protected members. They are declared with the friend keyword within the class and defined outside.
Friend functions help in situations where encapsulation needs to be maintained, but certain
operations require access to non-public members. They are particularly useful when working with
multiple classes that need to interact with each other's private data.
• Class Complex: Represents a complex number with real and imaginary parts.
• Constructor: Initializes the real and imaginary parts of a complex number. If no arguments
are provided, it initializes them to 0.
• Function add: Adds two complex numbers and returns the result as a new complex number.
• Function display: Displays the complex number.
• main function: Creates two complex numbers (num1 and num2), adds them using the add
function, and displays the result.
Output:
6. Write a program to exchange values between two classes using friend classes
#include <iostream>
using namespace std;
class A {
private:
int valueA;
public:
A(int val) : valueA(val) {}
class B {
private:
int valueB;
public:
B(int val) : valueB(val) {}
return 0;
}
Explanation:
• Classes A and B have private member variables valueA and valueB, respectively.
• The friend function exchangeValues is declared within both classes.
• The friend function can access private members of both classes.
• In the main function, two objects objA and objB of classes A and B are created with initial values.
• The exchangeValues function is called to exchange the values of valueA and valueB.
• The values before and after the exchange are displayed.
7. Create a class employee that includes firstname(type String), last name(type String) and a monthly salary. Create two
employee objects and display each object’s yearly salary. Give each employee a 10% raise and display each employee’s
yearly salary.
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string firstName;
string lastName;
double monthlySalary;
public:
// Constructor to initialize employee details
Employee(string fName, string lName, double salary) {
firstName = fName;
lastName = lName;
if (salary > 0)
monthlySalary = salary;
else
monthlySalary = 0;
}
int main() {
// Create two Employee objects
Employee emp1("John", "Doe", 5000);
Employee emp2("Jane", "Smith", 6000);
return 0;
}
Explanation:
• The Employee class has private member variables firstName, lastName, and monthlySalary.
• The constructor initializes the employee details (firstName, lastName, and monthlySalary). If the salary provided
is negative, it defaults to 0.
• The yearlySalary function calculates and returns the yearly salary.
• The giveRaise function increases the monthly salary by 10%.
• The display function displays the employee details and yearly salary.
• In the main function, two Employee objects (emp1 and emp2) are created with initial details and salaries.
• The initial yearly salaries of both employees are displayed.
• Each employee is given a 10% raise using the giveRaise function.
• The yearly salaries after the raise are displayed.
8. Write a C++ program that reads digits and computes them into integers. For example 123 is read as the characters 1,2 and
3. The program should output “123 is 1 hundred and 2 tens and 3 ones”. The number should be output as an int value.
Handle numbers with one, two, three or four digits. Hint: to get the integer value 5 of the character ‘5’ subtract ‘0’ that is ‘5’-
‘0’==5.
#include <iostream>
using namespace std;
int main() {
char digit1, digit2, digit3, digit4;
int num = (digit1 - '0') * 1000 + (digit2 - '0') * 100 + (digit3 - '0') * 10 + (digit4 - '0');
if (digit1 != '0') {
cout << (digit1 - '0') << " thousand ";
}
if (digit2 != '0') {
cout << (digit2 - '0') << " hundred ";
}
if (digit3 != '0') {
cout << (digit3 - '0') << " tens ";
}
if (digit4 != '0') {
cout << (digit4 - '0') << " ones ";
}
return 0;
}
Explanation:
• The program prompts the user to enter a four-digit number and reads each digit separately.
• It calculates the integer value of the four-digit number using the formula (digit1 - '0') * 1000 + (digit2 - '0') * 100 +
(digit3 - '0') * 10 + (digit4 - '0').
• It then prints the original number and breaks it down into its constituent digits, printing the corresponding integers
for thousands, hundreds, tens, and ones.
Sample Input/Output: