Tutorial Object Oriented Programming Using C++ CST 157
Tutorial Object Oriented Programming Using C++ CST 157
Q1. What are the advantages of dynamic memory allocation over the
compile time memory allocation?
Answer: Both malloc() and new are used to dynamically allocate variables,
however the two also show some differences:
new malloc()
1. new is an operator. 1. malloc() is a function.
2. new keyword could be used 2. malloc() is used to
to call constructors. It could dynamically allocate memory
dynamically declare objects only to primitive data types,
as well as primitive data i.e., int, float, char, etc.
types.
3. new returns exact data type of 3. malloc() returns void data
the pointer it is allocating. No type and needs typecasting to
need for typecast. decide the return type.
4. Required size of memory is 4. We need to calculate the
calculated by compiler for required size of data structure
new. to call malloc.
5. It never returns NULL, even in 5. It returns NULL in case of
case of fault, it throws. fault.
Answer: Using pointers in a program can have some benefits, and some
drawbacks as well. Some of the advantages and disadvantages of using
pointers are discussed below:
Advantages
Disadvantages
Answer:
#include<iostream>
using namespace std;
int main()
{
int *ptri = new int;
float *ptrf = new float(19.79);
char *ptrc = new char;
cout<<"Enter an integer : ";
cin>>*ptri;
cout<<"Enter an alphabet : ";
cin>>*ptrc;
cout<<"\nInteger :"<<*ptri<<"\nFloat :"<<*ptrf<<"\nCharacter :"<<*ptrc;
delete ptri, ptrf, ptrc;
return 0;
}
Output
Answer:
#include<iostream>
using namespace std;
class student
{
string name;
string uid;
float marks[5];
public:
void input()
{
cout<<"Enter name:";
cin>>name;
cout<<"Enter UID:";
cin>>uid;
cout<<"Enter marks for 5 subjects:\n";
for(int i=0;i<5;i++)
cin>>marks[i];
}
void output()
{
cout<<"\nName:"<<name<<"\nUID:"<<uid<<"\nMarks:\t";
for(int i=0;i<5;i++)
cout<<marks[i]<<" ";
}
};
int main()
{
int n;
cout<<"How many students' details you want to enter? \n";
cin>>n;
student *ptr = new student[n];
for(int i=0;i<n;i++)
{
ptr[i].input();
}
cout<<"\nDetails entered are as follows:";
for(int i=0;i<n;i++)
{
ptr[i].output();
}
delete []ptr;
return 0;
}