Using C++ (not C) to write a complete program that meets all of the following re
ID: 3576076 • Letter: U
Question
Using C++ (not C) to write a complete program that meets all of the following requirements.
Create a class called ABC with the following:
- a non-static data member: a char* (you'll be allocating memory dynamically for this one)
- A static data member: pi, initialized to 3.14
- Three constructors. A default ctor, a copy ctor, and another one
- If necessary, write a destructor.
- Overload the insertion operator so that it does something appropriate.
- Overload the ! operator so that it prints the static data member.
- Overload the assignment operator, so that you can assign one ABC object to another.
Write a main() that demonstrates at least one call to every function in the ABC class.
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
class ABC
{
char* data;
static float pi;
public:
ABC()
{
data=NULL;
}
ABC(char* s)
{
data=new char[strlen(s)-1];
strcpy(data,s);
}
ABC(const ABC& s)
{
cout<<"Calling copy constructor ";
data=new char[strlen(s.data)-1];
strcpy(data,s.data);
}
~ABC()
{
delete [] data;
}
friend ostream& operator <<(ostream& obj1,ABC& obj2)
{
cout<<"Print data member ";
obj1<<obj2.data<<endl;
return obj1;
}
void operator ! ()
{
cout<<"Print static data member ";
cout<<pi<<endl;
}
void operator =(const ABC& s)
{
cout<<"Calling Assignment operator ";
data=new char[strlen(s.data)-1];
strcpy(data,s.data);
}
};
float ABC::pi=3.14;
int main(int argc, char const *argv[])
{
char name[]="Akshay";
ABC o1(name);
cout<<o1;
!o1;
ABC o2=o1;
cout<<o2;
!o2;
ABC o3;
o3=o2;
cout<<o3;
!o3;
return 0;
}
===================================================================================
akshay@akshay-Inspiron-3537:~$ g++ ABC.cpp
akshay@akshay-Inspiron-3537:~$ ./a.out
Print data member
Akshay
Print static data member
3.14
Calling copy constructor
Print data member
Akshay
Print static data member
3.14
Calling Assignment operator
Print data member
Akshay
Print static data member
3.14
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.