0% found this document useful (0 votes)
49 views13 pages

Understanding C++ Pointers and OOP Concepts

The document provides an overview of various C++ programming concepts including arrays of pointers, operator overloading, scope resolution, function overloading, abstract classes, type casting, object-oriented programming principles, templates, copy constructors, exception handling, and stream classes. It includes code examples to illustrate these concepts and their applications. Additionally, it briefly mentions the features of the Java programming language.

Uploaded by

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

Understanding C++ Pointers and OOP Concepts

The document provides an overview of various C++ programming concepts including arrays of pointers, operator overloading, scope resolution, function overloading, abstract classes, type casting, object-oriented programming principles, templates, copy constructors, exception handling, and stream classes. It includes code examples to illustrate these concepts and their applications. Additionally, it briefly mentions the features of the Java programming language.

Uploaded by

Yash Chandekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1 a) An array of pointers is an array that consists of variables of pointer type, which means

that the variable is a pointer addressing to some other element. Suppose we create an array
of pointer holding 5 integer pointers; then its declaration would look like:

int *ptr[5]; // array of 5 integer pointer

In the above declaration, we declare an array of pointer named as ptr, and it allocates
5 integer pointers in memory.The element of an array of a pointer can also be
initialized by assigning the address of some other element. Let's observe this case
through an example.

int a; // variable declaration.

ptr[2] = &a;

In the above code, we are assigning the address of 'a' variable to the third element of
an array 'ptr'.

We can also retrieve the value of 'a' by dereferencing the pointer.

1. *ptr[2];

b) C++ is able to input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator <<. The stream insertion and stream

extraction operators also can be overloaded to perform input and output for user-defined

types like an object.

Following example explains how extraction operator >> and insertion operator <<

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}

friend istream &operator>>( istream &input, Distance &D ) {


input >> D.feet >> D.inches;
return input;
}
};

int main() {
Distance D1(11, 10), D2(5, 11), D3;

cout << "Enter the value of object : " << endl;


cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;

return 0;
}

c) The scope resolution operator ( :: ) is used for several reasons. For example: If the global
variable name is same as local variable name, the scope resolution operator will be used to
call the global variable. It is also used to define a function outside the class and used to
access the static variables of class.
Example:
#include <iostream>
using namespace std;
char a = 'm';
static int b = 50;

int main() {
char a = 's';

cout << "The static variable : "<< ::b;


cout << "The local variable : " << a;
cout << "The global variable : " << ::a;
return 0;
}
d) 1. Function name should be same and arguments must be different.
2. Parameters should have different type
add(int a,int b)
add(double a,double b)
3. Parameters should have a different number
add(int a,int b)
add(int a,int b,int c)
4. There should be difference in sequence of parameters
add(int a,double b)
add(double a,int b)
e) Sometimes implementation of all function cannot be provided in a base class because we
don’t know the implementation. Such a class is called abstract class. For example, let Shape
be a base class. We cannot provide implementation of function draw() in Shape, but we
know every derived class must have implementation of draw(). A pure virtual function (or
abstract function) in C++ is a virtual function for which we can have implementation, But we
must override that function in the derived class, otherwise the derived class will also become
abstract class
Example:
#include<iostream>
using namespace std;

class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};

int main(void)
{
Derived d;
d.fun();
return 0;
}
f) Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways: automatically by the compiler and manually by the
programmer or user. Type Casting is also known as Type Conversion.
Implicit type casting
#include <iostream>

using namespace std;

int main ()

short x = 200;

int y;

y = x;

cout << " Implicit Type Casting " << endl;

cout << " The value of x: " << x << endl;

cout << " The value of y: " << y << endl;

int num = 20;

char ch = 'a';

int res = 20 + 'a';

cout << " Type casting char to int data type ('a' to 20): " << res << endl;

float val = num + 'A';

cout << " Type casting from int data to float type: " << val << endl;

return 0; }
Explicit type casting
#include <iostream>

using namespace std;

int main ()

// declaration of the variables

int a, b;

float res;
a = 21;

b = 5;

cout << " Implicit Type Casting: " << endl;

cout << " Result: " << a / b << endl; // it loses some information

cout << " \n Explicit Type Casting: " << endl;

// use cast () operator to convert int data to float

res = (float) 21 / 5;

cout << " The value of float variable (res): " << res << endl;

return 0;

}
Q2. a) The object-oriented programming is basically a computer programming design
philosophy or methodology that organizes/ models software design around data, or objects
rather than functions and logic. An object is referred to as a data field that has unique
attributes and behavior. Everything in OOP is grouped as self-sustainable objects.OOPs
mainly works on Class, Object, Polymorphism, Abstraction, Encapsulation and
Inheritance.
Advantages
1. Troubleshooting is easier with the OOP language

2. Code Reusability

3. Productivity

4. Data Redundancy

5. Code Flexibility

6. Solving problems

7. Security

b) Every object in C++ has access to its own address through an important pointer called

this pointer. This pointer is an implicit parameter to all member functions. Therefore, inside a

member function, this may be used to refer to the invoking object. Friend functions do not

have a this pointer, because friends are not members of a class. Only member functions

have a this pointer


class Age

private:

int a;

public:

Age(int a = 0){

cout << "Address of object = " << this << endl;

this->a = a;

Age& setAge(int x){

cout << "Address of object = " << this << endl;

a = x;

return *this; //returns the current object

void getAge(){

cout << "Address of object = " << this << endl;

cout << "The age is " << a << endl;

};

int main() {
Age obj;

//we don't need to explicitly call getAge() now, we can call it on the returned object.

obj.setAge(20).getAge(); //(function chaining)

return 0;

Q3. a) Templates are the foundation of generic programming, which involves writing code in

a way that is independent of any particular type. A template is a blueprint or formula for

creating a generic class or a function.

Example:

#include <iostream>

using namespace std;

template <class T>

class myclass {

T a, b;

public:

myclass (T first, T second)

{a=first; b=second;}

T getMaxval ();

};

template <class T>

T myclass<T>::getMaxval ()

return (a>b? a : b);

int main () {
myclass <int> myobject (100, 75);

cout<<"Maximum of 100 and 75 = "<<myobject.getMaxval()<<endl;

myclass<char> mychobject('A','a');

cout<<"Maximum of 'A' and 'a' = "<<mychobject.getMaxval()<<endl;

return 0;

Template Function Overloading:

● The name of the function templates are the same but called with different
arguments is known as function template overloading.
● If the function template is with the ordinary template, the name of the function
remains the same but the number of parameters differs.

Code:

#include <bits/stdc++.h>

using namespace std;

// Template declaration

template <class T>

// Template overloading of function

void display(T t1)

cout << "Displaying Template: "

<< t1 << "\n";

}
// Template overloading of function

void display(int t1)

cout << "Explicitly display: "

<< t1 << "\n";

// Driver Code

int main()

// Function Call with a

// different arguments

display(200);

display(12.40);

display('G');

return 0;

b) #include<bits/stdc++.h>

using namespace std;

class nums{

int a;

public:

nums(int n){

a=n; }

int operator%(int n){


return a%n; }

friend void check_prime(nums&);};

void check_prime(nums& ob){

int c=0;

for(int i=1;i<=ob.a;i++){

if(ob%i==0) c++; }

if(c==2) cout<<"Number is prime";

else cout<<"Number is not prime"; }

int main(){

int n;

cin>>n;

nums obj(n);

check_prime(obj);

return 0;}

Q4 a) A copy constructor is a member function that initializes an object using another object

of the same class. In simple terms, a constructor which creates an object by initializing it with

an object of the same class, which has been created previously is known as a copy

constructor.

Advantages:
● Copy constructors make it easy to copy objects. STL containers require all content to
be copied and assigned.
● Copy constructors can be more efficient than copyfrom () solutions because they
combine construction and replication.
Disadvantages:
● An implicit copy of an object is one of the sources of error and performance problems
in C+ +.
● It also reduces the readability of the code and makes it difficult to track the delivery
and changes in the object subroutine.

b) #include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
ifstream fin; //opening text file
int vowel{0},consonant{0},size;
char ch;
string str;
cout << "Enter the file to open: ";
cin >> str;
fin.open(str.c_str(),ios::in|ios::out);
fin.seekg(0,ios::end); //bring file pointer position to end of file
size = fin.tellg(); //count number of bytes till current position for file pointer
fin.seekg(0,ios::beg); //bring position of file pointer to beginning of file
while(fin){
fin.get(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' ||
ch == 'O' || ch == 'U'){
vowel++;
}
else{
consonant++;
}
}
cout << "Vowels: " << vowel << endl;
cout << "Consonants: " << consonant << endl;
fin.close(); //closing file
return 0;
}

Q5 a) #include <iostream>
using namespace std;
int main()
{
int x = 1;
char a = 'a';
try{
if(x == 0){
throw x;;
}
if(a == 'a'){
throw a;
}
}
catch(...){
cout << "Exception Caught";
}
return 0;
}

b) #include<bits/stdc++.h>
using namespace std;
class alpha{
private:
int a,b;
public:
alpha(int a,int b){
this->a=a;
this->b=b;
}
~alpha(){
cout<<"destructor for alpha called";
}
};

class beta: public alpha{


private:
int c;
public:
beta(int a,int b,int c):alpha(a,b){
this->c=c;
}
void display(){
cout<<a<<' '<<b<<' '<<c;
}
~beta(){
cout<<"destructor for beta called";
}
};

int main(){
beta obj(1,2,3);
obj.display();
return 0;
}

Q6 a) Pure virtual functions are for when there's no sensible way to implement the function
in the base class. For example:
1. class Shape {
2. public:
3. virtual float area() const = 0;
4. };
You can write derived classes like Circle and Rectangle that implement area()
using the specific formulas for those kinds of shapes.

If your function can be implemented (in a useful way) in the base class, then go ahead
and implement it. Not all base classes need to be abstract. But some of them just
inherently are abstract, like Shape.

b) A virtual function in C++ is a base class member function that you can redefine in a
derived class to achieve polymorphism. You can declare the function in the base class using
the virtual keyword. Once you declare the function in the base class, you can use a pointer
or reference to call the virtual class and execute its virtual version in the derived class.
We use virtual functions to ensure that the correct function is called for an object, regardless
of the reference type used to call the function. They are basically used to achieve the
runtime polymorphism and are declared in the base class by using the virtual keyword
before the function.

Q7 a) In C++ stream refers to the stream of characters that are transferred between the
program thread and i/o. Stream classes in C++ are used to input and output operations on
files and io devices. These classes have specific features and to handle input and output of
the program. The iostream.h library holds all the stream classes in the C++ programming
language.
C++ provides the following predefined streams:
● cin
The standard input stream
● cout
The standard output stream
● cerr
The standard error stream, unit-buffered such that characters sent to this stream are
flushed on each output operation
● clog
The buffered error stream
All predefined streams are tied to cout. When you use cin, cerr, or clog, cout gets flushed
sending the contents of cout to the ultimate consumer.

b) Major Features of Java Programming Language:


● Simple.
● Object-Oriented.
● Platform Independent.
● Portable.
● Robust.
● Secure.
● Interpreted.
● Multi-Threaded

You might also like