Here is the code where i used composition. I removed the non-relevant functions to make it little easier to understand .When i run this code using parametrized constructor, it work fine. But if i use default constructor while initilizing it does not work, the code terminate in between.
#include <iostream>
using namespace std;
class link
{
const char* name;
public:
link() :name("null")
{};
link(const char n[]) :name(n)
{};
~link()
{
cout << "destructor called " << endl;
};
};
class webpage
{
private:
double height;
double width;
link* links;
public:
webpage() :height(10), width(10),links(new link[1])
{};
webpage(double hw, link* hyperlinks) :height(hw), width(hw), links(hyperlinks)
{ };
webpage(double h, double w, link* hyperlinks) :height(h), width(w), links(hyperlinks)
{ };
~webpage()
{
delete [] links;
cout << "page destructor called " << endl;
};
void showdata(int linkno)
{
cout << "height: " << height << endl;
cout << "width: " << width << endl;
cout << "links " << endl;
for (int i = 0; i < linkno; i++)
{
cout << "link #" << i + 1 << " = " << links[i].getname() << endl;
}
}
};
class website
{
private:
const char* name;
webpage* wpgs;
public:
website() :name("null"),wpgs(new webpage[1])
{};
website(const char n[], webpage* page) :name(n), wpgs(page)
{};
~website()
{
delete[] wpgs;
cout << "website destructor " << endl;
};
void showdata(int linkno, int pageno)
{
cout << "Website name: " << name << endl;
for (int j = 0; j < pageno; j++)
{
cout << "Webpage #" << j + 1 << " : " << endl;
wpgs[j].showdata(linkno);
}
}
};
int main(int argc, char* argv[])
{
link* link1=new link[2] {{"maha"},{"saira"}};
link* link2=new link[3] {{"areeb"},{"aima"},{"umair"}};
link* link3=new link[2] {{"ahmad"},{"azra"}};
link* link4=new link[4] {{"usama"},{"tyabba"},{"ali"},{"hamza"}};
webpage* page=new webpage[4] {{2,link1},{3.2,5.2,link2},{4,1,link3},{42,13,link4}};
website site("my website",page);
site.showdata(2,4);
}
the above code work fine but if i use default constructor like in below code
int main()
{
link* links;
webpage* page;
website site("website", page);
site.showdata(1, 1);
}
now it won't work. the code with terminate after a bit.
and generate error
error1 'links': unreferenced local variable
error2 uninitialized local variable 'page' used
How can I inlitialize using default constructor
please help.
All the conditions implemented in question are demand of problem statement.
You aren't using any constructor because links and page are pointers. Pointers do not have constructors.
Maybe you want this?
webpage page;
website site("website", &page);
Now because page is not a pointer the webpage default constructor will be called.
Or looking at the rest of your code, probably this is correct.
webpage* page = new webpage[1];
website site("website", page);
new webpage[1] calls the webpage default constructor.
Related
This code is showing error when I make an instance of the class website. The instance has to use the explicit constructor which I have defined in the class definition. So I am passing a string value in it. This value is being received by an array of character type in the constructor which then initializes a pointer pointing to that array. Please avoid giving complex answers.
#include<iostream>
#include<conio.h>
using namespace std;
class Links
{
private:
char *linkname;
public:
Links()
{
cout << "Links default constructor called." << endl;
};
Links(char n[]):linkname(n)
{
cout << "Links parameterized constructor called." << endl;
};
char getlinkname()
{
return *linkname;
}
void setlinkname(char n[])
{
linkname = n;
}
};
class Webpage
{
private:
double width;
double height;
Links link1;
Links link2;
public:
Webpage()
{
cout << "Webpage default constructor called." << endl;
};
Webpage(double w, double h) :width(w), height(h)
{
cout << "Webpage parameterized constructor called." << endl;
};
double getheight()
{
return height;
}
double getwidth()
{
return width;
}
void setheight(double h)
{
height = h;
}
void setwidth(double w)
{
width = w;
}
};
class Website
{
private:
char *name;
Webpage webpage1{24.5,37.2};
Webpage webpage2;
Webpage webpage3{10,18.7};
Webpage webpage4;
public:
Website()
{
cout << "Website default constructor called." << endl;
};
Website(char n[]):name(n)
{
cout << "Website parameterized constructor called." << endl;
};
char getname()
{
return *name;
}
void setname(char n[])
{
name = n;
}
};
int main()
{
Website w1("www.google.com");
_getch();
return 0;
}
String literals are 'const', try this:
class Website
{
private:
const char *name;
Webpage webpage1{24.5,37.2};
Webpage webpage2;
Webpage webpage3{10,18.7};
Webpage webpage4;
public:
Website()
{
cout << "Website default constructor called." << endl;
};
Website(const char* n):name(n)
{
cout << "Website parameterized constructor called." << endl;
};
const char* getname()
{
return name;
}
void setname(const char* n)
{
name = n;
}
};
So as the title suggests I am attempting to change the number variable, originally stored as 1000. Change this variable in another class function, and then replace the original value (1000) with the newly updated number. I haven't been able to find anything online to help me with this.
I have tried using pointers to no avail.
#include <iostream>
using namespace std;
class data {
protected:
int number = 1000;
};
class fetchData : public data {
public:
int getNumber() {
return number;
}
int updateNumber(int newNumber) {
number = newNumber;
return number;
}
};
class function : public fetchData {
public:
void minusNumber(int numberTakeAway) {
int newNumber = number - numberTakeAway;
updateNumber(newNumber);
cout << "Taken away: " << numberTakeAway << endl;
cout << "\nShould be new number: " << number << endl; // Not updating parent class variable
}
};
void printData() {
fetchData r;
cout << "number: " << r.getNumber() << endl;
}
void minusNumber() {
function r;
r.minusNumber(200);
}
int main(void) {
fetchData q;
cout << "\nOriginal ";
printData();
cout << "\n";
minusNumber();
cout << "\nActual ";
printData();
cout << "\n";
return 0;
}
You seem to be confusing between static - class members, and non static - instance members.
number is an instance member which means every instance will have its own number with its own value.
Each of your functions main, printData, and minusNumber creates its own instance of function or fetchData class, and there is no connection between them.
Try this code, where there is only one instance:
int main(void) {
function q;
cout << "\nOriginal ";
q.printData();
cout << "\n";
q.minusNumber(200);
cout << "\nActual ";
q.printData();
cout << "\n";
return 0;
}
What you have done in the free functions is to create a new instance of your class. If you want to do something with q that you instantiated in main, you have to pass it. Or use the member function in your class. So below, I've changed printData to take a reference to q. And instead of calling the free function minusNumber, I've called the member function of your class. I deleted the free function as it is not used.
#include <iostream>
class data {
protected:
int number = 1000;
};
class fetchData : public data {
public:
int getNumber() const {
return number;
}
int updateNumber(int newNumber) {
number = newNumber;
return number;
}
};
class function : public fetchData {
public:
void minusNumber(int numberTakeAway) {
int newNumber = number - numberTakeAway;
updateNumber(newNumber);
std::cout << "Taken away: " << numberTakeAway << std::endl;
std::cout << "\nShould be new number: " << number << std::endl; // Not updating parent class variable
}
};
void printData(const function& r) {
std::cout << "number: " << r.getNumber() << std::endl;
}
int main(void) {
function q;
std::cout << "\nOriginal ";
printData(q);
std::cout << "\n";
q.minusNumber(200);
std::cout << "\nActual ";
printData(q);
std::cout << "\n";
return 0;
}
So I have these classes:
In main I wrote an array of pointers:
student *arry[10];
How can I make each cell point to an object of a different class?
For example :
I want the cell 0 , 2 , 4
point to an object of class medstudent
using ( new statement )
thank you
here is class medStudent
#include<iostream>
#include"student.cpp"
using namespace std;
class medStudent:public student {
public :int clinicH;
public:
medStudent(int ch, string n , int i ):student(n,i){
setClinicH(ch);
cout << "New Medecine Student" << endl;
}
~medStudent(){
cout << "Medecine Student Deleted" << endl;
}
medStudent(medStudent & ms):student(ms){
cout << "New Copy Medecined Student" << endl;
}
medstudent(){
}
void setClinicH(int ch){
clinicH = ch;
}
int getClinicH()const{
return clinicH;
}
void print()const{
student::print();
cout << "Clinical Hours: " << getClinicH() << endl;
}
};
Here is class student:
#include <iostream>
//#include"medstudent.cpp"
using namespace std;
class student//:public medstudent
{
public :
static int numberOfSaeeds;
const int id;
string name;
public:
~student(){
cout << "Delete Student: " << getName() << " " << endl ;
}
student(string n, int i):id(i){
setName(n);
cout << "Student with args" << endl ;
}
void setName(string n){
name = n;
}
string getName()const{
return name;
}
void print()const{
cout << "My name is: " << name << endl;
cout << "My ID is: " << id << endl;
}
void setNOS(int nos){
numberOfSaeeds = nos;
}
int getNOS(){
return numberOfSaeeds;
}
void printAddress()const{
cout << "My address is " << this << endl;
}
student * getAddress(){
return this;
}
student(student & sc):id(sc.id){
name = sc.name;
setName(sc.getName());
cout << "New Object using the copy constructor" << endl;
}
};
Here is main code:
#include<iostream>
using namespace std;
#include"time.cpp"
#include "student.cpp"
//#include"medstudent.cpp"
int main(){
student a1("asa" , 2);
student * a[10];
a[3]= new student("jj", 22 );
a[0] = new medStudent();
}
Since you explicitly declare a medStudent constructor the compiler will not create a default constructor for your class. And when you do new medStudent(); you are (explicitly) trying to invoke the default constructor, which doesn't exist.
That will give you a build error, one that should have been very easy to diagnose if you read it and most importantly shown it to us (when asking questions about build errors, always include the complete and unedited error output, including any informational output, in the body of the question, together with the code causing the error).
The solution? Call the existing parameterized constructor. E.g. new medStudent("foo", 123).
By the way, if you want inheritance to work okay, and the base-class destructor to be called when deleting an object of a child-class, then you need to make the destructors virtual.
I am learner in C++ and I am into the topic of constructors and destructors. I have compiled the code below and it returns the undefined reference to Book::~Book() error. But when I comment out the destructor, it is working fine. I think I can create member functions after using destructors. What am I doing wrong here? I have written my code below for better undertsanding
class Book
{
private:
int *pages;
int *price;
public:
Book() //default constructor
{
pages = new int;
price = new int;
*pages = 300;
*price = 8;
};
void pre_destructor()
{
std::cout << "The pages:" << *pages;
std::cout << "The price:" << *price;
}
~Book(); //destructor
void post_destructor()
{
std::cout << "The pages:" << *pages << "\n";
std::cout << "The price:" << *price << "\n";
delete pages;
delete price;
}
};
int main()
{
using namespace std;
Book book1;
cout << "Before using destructors" << endl;
cout << "---------------------------------"<< endl;
book1.pre_destructor();
cout << "After using destructors" << endl;
cout << "---------------------------------";
book1.post_destructor();
return 0;
} //destructor is called here
I've shortened that a little. the former void pre_destructor() was pointless; that's better placed in the dtor (short for "destructor") itself,
and the post_destructor() was even potentially harmful.
#include <iostream>
class Book
{
private:
int *pages;
int *price;
public:
Book() : pages(new int(300)), price(new int(8)) {}
~Book() {
std::cout << "The pages:" << *pages << "\n";
std::cout << "The price:" << *price << "\n";
delete price;
delete pages;
}
};
int main()
{
{
Book book1;
} //destructor is called here
return 0;
}
live at Coliru's
Your destructor is declared, but never defined.
Looks like "post_destructor" does the actual destruction. As a result, all you need to do is write you destructor as follows:
~Book() {} // empty, nothing to do here...
I want to display the objects of the class and the number of objects by using a static function. I typed this code but it does not work. It gives an error Too many types indeclaration" and "undefined symbol getCount. Can anyone help me? where is actually error in this code?
#include<iostream>
#include<string>
class Bag {
private:
static int objectCount;
int Weight;
std::string Brand;
std::string Type;
std::string Material;
std::string Colour;
public:
Bag(int W, std::string B, std::string T, std::string M, std::string C) {
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
std::cout << "\n";
std::cout << "Bag: \n\n";
std::cout << "Weight:\t\t" << Weight << "kg" << '\n';
std::cout << "Brand:\t\t" << Brand << '\n' << "Type:\t\t" << Type << '\n';
std::cout << "Material:\t" << Material << '\n' << "colour:\t\t" << Colour << std::endl;
}
static int getCount() {
return objectCount;
}
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
bag_1.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
bag_2.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
bag_3.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_4.print();
std::cout << "object count " << Bag::getCount() << std::endl;
while(!std::cin.get());
return 0;
}
You are scoping it incorrectly, getCount is statically scoped to the translation
unit, not the class. Thus it has no symbol named objectCount available to it.
To fix it, merely put the method inside the class.
class Bag {
private:
static int objectCount;
int Weight;
string Brand,Type,Material,Colour;
public:
Bag(int W ,string B ,string T,string M,string C)
{
Weight=W;
Brand=B;
Type=T;
Material=M;
Colour=C;
objectCount++;
}
void print()
{
cout<<"\n";
cout<<"Bag: \n\n";
cout<<"Weight:\t\t"<<Weight<<"kg"<<endl;
cout<<"Brand:\t\t"<<Brand<<endl<<"Type:\t\t"<<Type<<endl;
cout<<"Material:\t"<<Material<<endl<<"colour:\t\t"<<Colour<<endl;
}
static int getCount()
{
cout<< objectCount;
}
};
Aditionally, Borland is a really old compiler and suprised to even still
hear it's name, last release was around 15 years ago so you should really
consider using clang, gcc or msvc and upgrading your learning materials to
something less ancient. There has been alot of evolution in terms of practices,
standards and compiler conformance.
For example, C++ headers don't have an extension, and other small things like that.
This is a working version of your code:
#include <iostream>
#include <cstring>
using namespace std;
class Bag {
private:
static int objectCount;
int Weight;
string Brand, Type, Material, Colour;
public:
Bag(int W, string B, string T, string M, string C) //constructor
{
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
cout << "\n";
cout << "Bag: \n\n";
cout << "Weight:\t\t" << Weight << "kg" << endl;
cout << "Brand:\t\t" << Brand << endl << "Type:\t\t" << Type << endl;
cout << "Material:\t" << Material << endl << "colour:\t\t" << Colour
<< endl;
}
static int getCount() //static function to count objects
{
cout << objectCount;
};
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_1.print();
cout << "object count" << Bag::getCount();
bag_2.print();
cout << "object count" << Bag::getCount();
bag_3.print();
cout << "object count" << Bag::getCount();
bag_4.print();
cout << "object count" << Bag::getCount();
}
There were several mistakes in the version you posted:
in C++ you don't need the .h when including files
you were using cout without the std:: qualifier or adding using namespace std; to your source. Also, please read this.
your static function was not declared/defined inside your class definition
it should be int main instead of void main
One last note: I removed your #include <conio.h> which should probably read #include <conio> and getch because I compiled this on a linux machine. Feel free to add them back in if you want them.