Chapter - 5: Classes in C++

Point out the errors if any, in the following programs:


B
Sections
1
Exercises

A

B

C

D

1

(a)

#include<string>
using namespace std;
class address
{
	private:
		char name[10];
		char city[10];
	public:
		address(char *p, char *q)
		{
			strcpy(name, p);
			strcpy(city, q);
		}
};

//main follows here
int main()
{
	
	address my("Mac", "London");
	return 0;
}

No Error. (Some compilers may report error due to missing default constructor)


(b)

class date
{
	private:
		int day, month, year;
		date()
		{
			day = 7;
			month = 9;
			year = 1997;
		}
};

int main()
{
	date today;
	return 0;
}

Error: date() constructor is private.


(c)

#include<iostream>
using namespace std;

class value
{
	private:
		int i;
		float f;
	public:
		val()
		{
			i = 0;
			f = 0.0;
			return 1;
		}
};

int main()
{
	val v1;
	return 0;
}

Error:
1. val is not defined variable.
2. constructor/destructor can not return a value.


(d)

#include<iostream>
using namespace std;

class triplets
{
	private:
		int t1, t2, t3;
	public:
		trpilets(int x, int y, int z)
		{
			t1 = x;
			t2 = y;
			t3 = z;
		}
		void display()
		{
			cout << endl << t1 << t2 << t3;
		}
};

int main()
{
	triplets r(2,3,4), s;
	r.di0splay();
	s.diaplay();
	return 0;
}

Error: Constructor with zero arguments must be explicitly provided.


(e)

#include<iostream>
using namespace std;

class sample
{
	private:
		int data1;
		float data2;
	public:
		void sample();
		void displaydata();
};

int main()
{
	sample s;
	s.showdata();
	return 0;
}

sample void::sample()
{
	sata1 = 10;
	data2 = 20;
}

sample::void showdata()
{
	cout << endl << data1 << data2;
}

Error:

1. A constructor cannot be declared with a return type.
2. Function definition syntax is wrong.
(Right syntax: void sample::showdata(); )


(f)

#include<iostream>
using namespace std;

class list
{
	private:
		class node
		{
			int data;
			node *link;
		}*p;
	public:
		void create()
		{
			p = new node;
			p.data = 10;
			p->data = 10;
		}
};

int main()
{
	list l1;
	l1.create();
	return 0;
}

Error: Dot operator cannot be used to access member variable using a pointer.

 


© 2020 Garbage Valuegarbage value logo