CT1 Ans
CT1 Ans
Q. Write a C++ program to define and test the functions of the following class. Do not use any
“cstring” or “string” library function.
class SafeString {
char *str;
public:
SafeString(char *s) ; //Constructor safely copies string s into string str
/* Destructor releases the allocated memory of str when a SafeString object goes out of scope */
~SafeString() ;
int length(char *s); //Returns the length of the string s
bool equals(char *s); //Boolean function returns true if strings str and s are same
void concatenates(char *s); //Safely concatenates s at the end of str
};
Answer:
#include <iostream>
using namespace std;
class SafeString {
char *str;
public:
SafeString(char *s) ; //Constructor safely copies string s into string str
/* Destructor releases the allocated memory of str when a SafeString object goes out of scope */
~SafeString() ;
int length(char *s); //Returns the length of the string s
bool equals(char *s); //Boolean function returns true if strings str and s are same
void concatenates(char *s); //Safely concatenates s at the end of str
char *getstr();
};
SafeString::SafeString(char *s){
int i, l;
l=length(s);
str=new char[l+1];
for(i=0;s[i];i++){
str[i]=s[i];
}
str[i]='\0';
}
SafeString::~SafeString(){
delete []str;
}
char *SafeString::getstr(){
return str;
}
int main(){
char str1[80]="I love C++";
char str2[80]="I love Bangladesh";
char str3[80]="I love C++";
SafeString s(str1);
cout<<s.getstr()<<endl;
if(s.equals(str3)){
cout<<"s.str is equal to str3"<<endl;
}
if(s.equals(str2)){
cout<<"s.str is equal to str2"<<endl;
}
s.concatenates(str2);
cout<<s.getstr()<<endl;
return 0;
}