0% found this document useful (0 votes)
10 views12 pages

Comp Sci

The document provides an overview of key concepts in C++ programming, including virtual functions, object-oriented programming benefits, derived data types, classes and objects, and various types of constructors. It also covers exception handling, access specifiers, and the process of passing arrays to functions. Additionally, it explains inheritance types and constructor overloading in C++.

Uploaded by

ubaid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

Comp Sci

The document provides an overview of key concepts in C++ programming, including virtual functions, object-oriented programming benefits, derived data types, classes and objects, and various types of constructors. It also covers exception handling, access specifiers, and the process of passing arrays to functions. Additionally, it explains inheritance types and constructor overloading in C++.

Uploaded by

ubaid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

B.Sc.

First Year Second Semester


Subject: Comp-Sci-II (Programming in C++)

Virtual Member Function in C++


A virtual function (also known as virtual methods) is a member function that is declared
within a base class and is re-defined (overridden) by a derived class. When you refer to a
derived class object using a pointer or a reference to the base class, you can call a virtual
function for that object and execute the derived class’s version of the method.
Example:
#include <iostream.h>
class base {
public:
virtual void print() { cout << "print base class\n"; }
void show() { cout << "show base class\n"; }
};

class derived : public base {


public:
void print() { cout << "print derived class\n"; }
void show() { cout << "show derived class\n"; }
};

Benefits of object oriented languages?


Object-oriented programming (OOP) languages—like Java, Python, C++, and C#—bring a bunch of benefits to the
table, especially when building complex and large-scale software. Here's a breakdown of the main advantages:
1. Modularity: Code is organized into classes and objects.
2. Reusability: Thanks to inheritance, you can create new classes based on existing ones.
3. Encapsulation: Data and methods are bundled together.
4. Abstraction: Lets you focus on what an object does rather than how it does it.
5. Inheritance: A class can inherit properties and behaviors from another.
6. Polymorphism: One interface, many implementations.

DERIVED DATA TYPES IN C++


In C++, derived data types are types that are built upon the fundamental (primitive) data types. They are used to
create more complex data structures and to model real-world entities more effectively. These types extend the
capabilities of the basic data types provided by the language.
Common Derived Data Types:
1. Arrays: A collection of elements of the same type, stored in contiguous memory.
Example: int arr[5];
2. Pointers: Variables that store the memory address of another variable.
Example: int* ptr;
3. References: An alias for another variable; used mainly for function arguments and return types.
4. Example:: int& ref = var;
5. Classes and Structures (User-defined, but can be seen as derived from basic types): Used to define objects
with attributes and behaviors.

CLASSES & OBJECTS IN C++?


C++ is an object-oriented programming language, and classes and objects are at the core of OOP. They help
organize code and model real-world entities.
Class: A class is a user-defined data type that acts as a blueprint for creating objects. It defines properties (data
members) and behaviors (member functions).
Example:
class Car {
public:
string brand;
int year;
void display() {
cout << brand << " - " << year << endl;
}
};
Object: An object is an instance of a class. It holds actual values for the properties defined in the class.
Example:
Car myCar; //here myCar is an object of class Car
myCar.brand = "Toyota";
myCar.year = 2022;

myCar.display(); // Output: Toyota - 2022


return 0;
}

Applications of object oriented Programming


1. Software Development:OOPs, are widely used in software development because it allows developers to design
modular and reusable code
2. GUI Development: OOPs lends itself well to GUI development, giving a natural approach to model and
representing graphical elements
3. Game Development:OOPs are commonly used in game development due to their ability to express game things
as objects. Complex interactions between people, objects, and settings are common in games.
4. Desktop applications
5. Web applications
6. CAD/CAM Software

PRIMITIVE DATA TYPES IN C++


Primitive data types in C++ are some inbuilt data types that can be used by the user directly for the declaration of
the variable. Some primitive data types in C++ are:
1) Integer: 10,20,30
2) Character: ‘x’ ‘?’
3) Boolean: ture false
4) Floating Point: 1.5 123.456
5) Double Floating Point: 123.1234567
6) Valueless or Void

INSTANCE MEMBERS
In C++, instance data members, also called instance variables or object variables, are data members of a class that
are associated with each specific instance (object) of that class. Each object of the class gets its own independent
copy of the instance data members.
class Dog {
public:
std::string name; // Instance data member
int age; // Instance data member
};

C++ program to generate 10 terms of Fibonacci series


#include <iostream.h>
void main() {
int n=3, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
cout << t1 << ", ";
cout << t2 << ", ";
while (n<=10)
{
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
}
Output:
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

LONG ANSWER TYPES QUESTIONS


TOKEN AND TYPES IN C++
In C++, a token represents the smallest individual unit of a program that holds meaning for the compiler. The C++
parser recognizes several types of tokens, which are essential for constructing syntactically correct and meaningful
code.
1) Keywords: These are reserved words with predefined meanings in the C++ language. They cannot be used as
identifiers. Examples include int, float, class, if, else, for, while, etc.
2) Identifiers: These are names given to variables, functions, classes, and other user-defined elements. Identifiers
must begin with a letter or underscore and can contain letters, digits, and underscores. For example, myVariable,
Area, Data are valid identifiers.
3) Literals: These are constant values that are directly represented in the code. C++ has several types of literals,
including:
4) Numeric literals: Represent numerical values, such as 10 (integer), 3.14 (floating-point), and 2.5e-3
(exponential).
5) Character literals: Represent single characters enclosed in single quotes, such as 'A', 'b', and '\\n' (newline
character).
6) String literals: Represent sequences of characters enclosed in double quotes, such as "Hello, world!".
7) Boolean literals: Represent truth values, either true or false.
8) Pointer literals: Represent memory addresses, with the most common one being nullptr (representing a null
pointer).
9) Operators: These are symbols that perform specific operations on operands. C++ has a rich set of operators,
including arithmetic operators (+, -, *, /), comparison operators (==, !=, >, <), logical operators (&&, ||, !),
assignment operators (=, +=, -=), and more.

CONSTRUCTOR AND DIFFERENT TYPES OF CONSTRUCTORS


In C++, constructor is a special method that is invoked automatically at the time an object of a class is created. It is
used to initialize the data members of new objects. The constructor in C++ has the same name as the class or
structure.
Example:
#include <iostream.h>
class car {
public:
// Constructor of the class without parameters
car( ) { cout << "Constructor called" << endl; }
};
Types of Constructors in C++
Constructors can be classified based on in which situations they are being used. There are 4 types of constructors in
C++:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor
A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is also called a zero-
argument constructor. The compiler automatically creates an implicit default constructor if the programmer does
not define one.
2. Parameterized Constructor
Parameterized constructors make it possible to pass arguments to constructors. Typically, these arguments help
initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way
we would to any other function.
Example:
#include <iostream>
using namespace std;
class A {
public:
int val;
// Parameterized Constructor
A(int x) { val = x; }
};
3. Copy Constructor
A copy constructor is a member function that initializes an object using another object of the same class. Copy
constructor takes a reference to an object of the same class as an argument.
Example:
#include <iostream>
using namespace std;
class A {
public:
int val;
// Parameterized constructor
A(int x) { val = x; }
// Copy constructor
A(A& a) { val = a.val; }
};
CONCEPT OF INHERITANCE ,TYPES WITH EXAMPLES.
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one
of the most important feature of Object Oriented Programming. Sub Class: The class that inherits properties from another
class is called Sub class or Derived Class. Super Class:The class whose properties are inherited by sub class is called Base
Class or Super class.
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is
inherited by one base class only.
// Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{ cout << "This is a Vehicle" << endl; }
};
// sub class derived from two base classes
class Car: public Vehicle{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. i.e one sub class is inherited from more than one base class.
// C++ program to explain multiple inheritance
#include <iostream.h>
// first base class
class Vehicle {
public:
Vehicle()
{ cout << "This is a Vehicle" << endl; }
};
// second base class
class FourWheeler {
public:
FourWheeler()
{ cout << "This is a 4 wheeler Vehicle" << endl; }
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{ cout << "This is a Vehicle" << endl; }
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{ cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

CONSTRUCTOR OVERLOADING IN C++


In C++, We can have more than one constructor in a class with same name, as long as each has a different list of
arguments. This concept is known as Constructor Overloading and is quite similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class) and different by number and
type of arguments. A constructor is called depending upon the number and type of arguments passed. While
creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
// Constructor overloading
#include <iostream>
using namespace std;
class car
{
public:
float area;
// Constructor with no parameters
car()
{ area = 0; }
// Constructor with two parameters
car(int a, int b)
{ area = a * b; }

void disp()
{ cout<< area<< endl; }
};

int main()
{
// Constructor Overloading ith two different constructors of class name
car car1;
car car2( 10, 20);

car1.disp();
car2.disp();
return 1;
}
Output:

0
200

EXPLAIN THE USE OF TRY, CATCH, AND THROW KEYWORDS WITH AN EXAMPLE.
An exception is an unexpected event that occurs during program execution. For
example,divide_by_zero = 7 / 0;
The above code causes an exception as it is not possible to divide a number by 0.The
process of handling these types of errors in C++ is known as exception handling.In C++,
we handle exceptions with the help of the try and catch blocks, along with the throw
keyword.
try - code that may raise an exception
throw - throws an exception when an error is detected
catch - code that handles the exception thrown by the throw keyword
Note: The throw statement is not compulsory
Syntax for Exception Handling in C++
try {
// code that may raise an exception
throw argument;
}
catch (exception) {
// code to handle exception
}
When an exception occurs, the throw statement throws an exception, which is caught by
the catch block.
The catch block cannot be used without the try block.
Example: C++ Exception Handling
// program to divide two numbers
// throws an exception when the divisor is 0
#include <iostream>
using namespace std;
int main() {
double n, d, divide;
cout<< "Enter numerator: ";
cin>> n;
cout<< "Enter denominator: ";
cin>> d;
try {
// throw an exception if denominator is 0
if (d == 0)
throw 0;
// not executed if denominator is 0
divide = n / d;
cout<< n << " / " << d << " = " << divide <<endl;
}
catch (intnum_exception) {
cout<< "Error: Cannot divide by " <<num_exception<<endl;
}
return 0;
}
Run Code
Output
Enter numerator: 72
Enter denominator: 0
Error: Cannot divide by 0
DIFFERENCE BETWEEN PRIVATE, PROTECTED, AND PUBLIC ACCESS SPECIFIERS IN C++.
Access Specifiers in C++
Access specifiers define how members (variables and functions) of a class can be accessed from outside the
class or in derived classes.
There are three main access specifiers:
1. private
 Default access level for class members.
 Accessible only within the class.
 Not accessible from outside the class or by derived classes.
class MyClass {
private:
int secret;

public:
void setSecret(int s) {
secret = s; // OK
}
};
2. protected
 Similar to private, but with one exception:
 Accessible within the class and by derived classes.
 Still not accessible from outside the class.
class Base {
protected:
int value;
};

class Derived : public Base {


public:
void setValue(int v) {
value = v; // OK, accessible in derived class
}
};
3. public
 Accessible from anywhere: inside the class, in derived classes, and outside the class (through objects).
cpp
CopyEdit
class MyClass {
public:
int number;
};

Comparison Table:
Access Specifier Within Class Derived Class Outside Class
private Yes No No
protected Yes Yes No
public Yes Yes Yes

class Example {
private:
int a; // Only accessible inside class
protected:
int b; // Accessible in class and derived class
public:
int c; // Accessible everywhere
WHAT IS ARRAY? EXPLAIN THE PROCESS OF PASSING ARRAYS TO FUNCTIONS
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows
multiple values to be stored under one name, using an index.
Syntax:
type arrayName[size];
Example:
int numbers[5] = {10, 20, 30, 40, 50};
 numbers[0] = 10, numbers[1] = 20, etc.
 Index starts from 0.
Passing Arrays to Functions in C++
In C++, you can’t pass the whole array directly by value. Instead, you pass:
 A pointer to the first element of the array.
 Optionally, the size of the array as a separate parameter.
Passing 1D Array to Function
Function Definition:
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
Function Call:
int main() {
int numbers[] = {1, 2, 3, 4, 5};
display(numbers, 5);
return 0;
}

DYNAMIC MEMORY ALLOCATION PROCESS WITH SUITABLE EXAMPLE


Dynamic memory allocation in C++ allows you to allocate memory during runtime, rather than at compile
time. This is useful when the size of the data you need to store is not known until the program is running, or
when you need to allocate a large amount of memory. The new and delete operators are used for dynamic
memory allocation and deallocation respectively.
#include <iostream>
int main() {
// Allocate memory for an integer using new
int *ptr = newint; // 'new int' allocates
memory for an integer
// Assign a value to the memory
*ptr = 20;

// Print the value


std::cout<< "Value stored in dynamically
allocated memory: " << *ptr<<std::endl;

// Deallocate the memory using delete


deleteptr; // 'delete ptr' frees the memory pointed to by ptr
return 0;
}

You might also like