answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How can you use turbo c in mac?

Only if it has a MSDOS-emulator -- not likely.

Does the derived class take the memory of base class in inheritance?

Yes, the derived class includes the memory of the base class. The derived class inherits everything in the base class, data and function, and provides additional data and function as needed.

What are the privileges granted to friend function?

Friend functions (and classes) have private access to the classes that declare them as friends. Although they have the same access rights as members of the class itself, friends are not themselves members of the class and cannot be inherited.

Which library header is to make sqrt function?

#include <cmath> // simple version #include <complex> // complex version

Is it true that by base class pointer you can call only those functions of derived class which are inherited from the base class?

Yes, provided those functions are declared virtual. If they are not virtual, the base class method is implicitly called instead. The base class should be thought of as a common interface to the objects that derive from it, while the derived objects are "more specialised" forms of the base class, which can override the virtual base class methods to produce more specific behaviour. The less derived the object, the less specialised it becomes.

Certain functions can be predicted for all derived objects, but cannot be implemented in the base class. For instance, all shapes can be drawn, but a shape base class cannot implement a Draw() function unless it knows what type of shape it actually is. But by deriving specific shapes such as circles and squares from the shape class, they can each provide their own implementations for the Draw() function, which can then be declared pure-virtual in the base class. This not only ensures that every derived shape provides its own Draw() method, but also ensures that no instances of shape can be created other than by derived objects. The shape then becomes abstract; so shape is a conceptual object while circles and squares are actual objects.

Why are the indents necessary after the if and else statement?

Indents are not necessary for simple if statements:

if (true) /* do something */ ;

else /* do something */;

However, when a statement is a compound statement, it's best to place the statement body on a separate line and indent it:

if (true) {

/* do something */ ; /* do something */ ; /* do something */ ;

} else {

/* do something */;

/* do something */;

}

The indents help the reader; separating the controlling expressions from the compound statements and thus exposing the structure of the if statement itself.

Example of lazy copy in c plus plus?

Lazy copying is a hybrid of the standard shallow-copy and deep-copy mechanisms. Objects that are copy constructed or assigned from existing instances will initially be shallow-copied, meaning their dynamic data members will share the same memory. When an object is mutated whilst sharing memory, its data will be deep copied so as not to affect the shared instances.

In other words, deep-copying is postponed until it is actually required (if at all). For large and complex objects, this can offer a significant memory saving and a major performance boost as a shallow copy is significantly faster than a deep copy, and sharing memory obviously consumes less memory.

In order to implement lazy copying, it is necessary for each instance to be fully aware of all the instances it shares memory with. One of the simplest ways of achieving that is for each instance to maintain bi-directional pointers, similar to those you would find in a doubly-linked list. However, unlike a linked list, there is no need to expose these pointers outside of the class as the class can link and unlink all by itself, via the copy constructor and the assignment operator. All the functionality is encapsulated within the class so the lazy copy mechanism is completely transparent to the end user.

The following implementation provides a brief demonstration of how the mechanism works. It is by no means a complete implementation as it can only handle one type of data, but it serves to demonstrate the key aspects of lazy copying. A more complete implementation would change the data to a template class, thus allowing any type of data to be lazy copied.

The output shows that while each instance of the object occupies separate memory locations, the data they contain is initially shared. We then manipulate the objects to show that deep copying is occurring when it is required, and that destroying a share doesn't affect any remaining shares. If you strip away the trace code in the main function you will see that the lazy copy mechanism is completely transparent; you need never know it exists as it is fully encapsulated within the Object class itself.

// Demonstration of a lazy copy mechanism

// Copyright ©PCForrest, 2012

#include <iostream>

using namespace std;

// Example data container.

class Data

{

friend ostream& operator<<(ostream& os, const Data& data);

public:

inline ~Data(){delete(m_num);}

inline Data():m_num(new int(0)){}

inline Data(const int num):m_num(new int(num)){}

inline Data(const Data& data):m_num(new int(*data.m_num)){}

inline Data& operator=(const Data& data){*m_num=*data.m_num; return(*this);}

inline Data& operator=(const int num){*m_num=num; return(*this);}

inline bool operator==(const Data& data){return(*m_num==*data.m_num);}

inline bool operator!=(const Data& data){return(*m_num!=*data.m_num);}

inline int operator+(const Data& data){return(*m_num+*data.m_num);}

inline int operator+(const int num){return(*m_num+num);}

inline Data& operator+=(const Data& data){*m_num+=*data.m_num; return(*this);}

inline Data& operator+=(const int num){*m_num+=num; return(*this);}

inline int GetNum()const{return(*m_num);}

inline void SetNum(const int num){*m_num=num;}

private:

int * m_num;

};

// Friend function

ostream& operator<<(ostream& os, const Data& data)

{

os<<"Data:0x"<<&data<<" ("<<*data.m_num<<")";

return(os);

}

// Lazy copy class.

class Object

{

friend ostream& operator<<(ostream& os, const Object& object);

public:

inline Object():m_nextshare(NULL),m_prevshare(NULL),m_data(new Data(0)){}

inline Object(const Object& object):m_prevshare(&object.LocateLastShare()),m_nextshare(NULL),m_data(object.m_data){m_prevshare->m_nextshare=this;}

inline ~Object(){if(IsShared())UnlinkShare();else delete( m_data ); m_data = NULL;}

Object& operator=(const Object& object);

Object& operator+=(const Object& object);

inline Data GetData()const{return( *m_data);}

void SetData(const Data& data);

private:

inline bool IsShared()const{return(m_prevshare!=NULL m_nextshare!=NULL);}

Object& LocateLastShare()const;

Object* LocateShare(const Object & object)const;

void UnlinkShare();

mutable Object * m_nextshare;

mutable Object * m_prevshare;

Data * m_data;

};

// Friend function

ostream& operator<<(ostream& os, const Object& object)

{

os<<"Object:0x"<<&object<<"\t"<<*object.m_data;

return(os);

}

// Assign (implements shallow-copy)

Object& Object::operator=(const Object& object)

{

if( &object != this && // Not a self-reference.

!LocateShare(object) ) // Not already shared.

{

// Unlink or destroy data.

if( IsShared() )

UnlinkShare();

else if( m_data )

delete( m_data );

// Shallow-copy.

m_data = object.m_data;

// Link to new shares.

m_prevshare = &object.LocateLastShare();

m_prevshare->m_nextshare = this;

}

return(*this);

}

// Add/assign (implements deep-copy)

Object& Object::operator+=(const Object& object)

{

if( IsShared() )

{

UnlinkShare();

m_data = new Data( *m_data + *object.m_data );

}

else

*m_data += *object.m_data;

return( *this );

}

// Returns a reference to the last shared instance of this instance.

Object& Object::LocateLastShare()const

{

Object* p=(Object*)this;

while(p && p->m_nextshare)

p=p->m_nextshare;

return(*p);

}

// Returns a pointer to the given object if it is amongst the shared instances

// of this instance. Returns NULL if the object is this instance or is not shared.

Object* Object::LocateShare(const Object& object)const

{

// Search previous instances first.

Object* p=m_prevshare;

while( p && p!=&object)

p=p->m_prevshare;

if(!p)

{

// Not found, search next instances:

p = m_nextshare;

while( p && p!=&object) p=p->m_nextshare;

}

return(p);

}

// Unlinks this object from its shared instances.

void Object::UnlinkShare()

{

// Update the links on either side first.

if(m_nextshare) m_nextshare->m_prevshare=m_prevshare;

if(m_prevshare) m_prevshare->m_nextshare=m_nextshare;

m_nextshare=NULL;

m_prevshare=NULL;

}

// Mutator. Implements deep copy if incoming data differs.

void Object::SetData(const Data& data)

{

if( *m_data != data )

{

if( IsShared() )

{

UnlinkShare();

m_data = new Data(data);

}

else

*m_data = data;

}

}

// Demonstration program:

int main()

{

Object a;

a.SetData( 5 );

Object b = a; // Assign (lazy copy)

Object* c = new Object(b); // Copy construct (lazy copy)

cout<<"Original memory:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

b += a; // Deep copy.

cout<<"After mutating b:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

delete(c);

cout<<"After destroying c:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<endl;

// Instantiate a new, unshared instance

c = new Object();

cout<<"After instantiating c as new:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

// Assign b to c

*c = b;

cout<<"After reassigning c:"<<endl;

cout<<"a\t"<<a<<endl;

cout<<"b\t"<<b<<endl;

cout<<"c\t"<<*c<<endl;

cout<<endl;

return(0);

}

Output:

Original memory:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x003577B8 (5)

c Object:0x00211F58 Data:0x003577B8 (5)

After mutating b:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x003577B8 (5)

After destroying c:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

After instantiating c as new:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x003578A8 (0)

After reassigning c:

a Object:0x001FFA20 Data:0x003577B8 (5)

b Object:0x001FFA0C Data:0x00357818 (10)

c Object:0x00211F58 Data:0x00357818 (10)

What are the four components of an interface?

electrical component, mechanical component, functional component and procedural component

Why you need to declare variable 1st in turbo c plus plus?

In C++ all names (including variables) must be declared before they can be used.

Write a standard lock plus double check to create a critical section around a variable access?

using System; using System.Text; using System.Threading; namespace thread01 { public class Counter { private int _count=0; private int _even=0; public int Count { get { return _count; } } public int EvenCount { get { return _even; } } private Object theLock = new Object(); public void UpdateCount() { lock (theLock) { _count = _count + 1; if (Count % 2 == 0) // An even number { _even += 1; } } } } class Program { static void Main(string[] args) { Counter count = new Counter(); ParameterizedThreadStart starter = new ParameterizedThreadStart(Program.UpdateCount); Thread[] threads = new Thread[10]; for (int x = 0; x < 10; ++x) { threads[x] = new Thread(starter); threads[x].Start(count); } for (int y = 0; y < 10; ++y) { threads[y].Join(); } Console.WriteLine("Total: {0} - Even: {1}", count.Count,count.EvenCount); Console.ReadKey(); Console.ReadKey(); } static void UpdateCount(object param) { Counter count = (Counter)param; for (int z = 1; z

How a program in c plus plus plus plus using function that returns the smallest of three floating-point numbers?

#include <iostream>

using std::cin;

using std::cout;

using std::endl;

double minimum(double arg1, double arg2, double arg3);

int main()

{

cout << "Enter first number: ";

double firstNumber = 0.0;

cin >> firstNumber;

cout >> "Enter second number: ";

double secondNumber = 0.0;

cin >> secondNumber;

cout << "Enter third number: ";

double thirdNumber = 0.0;

cin >> thirdNumber;

cout << "\nThe smallest number is " << minimum(firstNumber, secondNumber, thirdNumber) << endl;

return 0;

}

//All three arguments have to be different

double minimum(double arg1, double arg2, double arg3)

{

double min = arg1;

if (arg 1 > arg2)

{

min = arg2;

}

else if (arg1 > arg3)

{

min = arg3;

}

return min;

}

Can we create an array of objects for a class having default constructor Justify your answer?

See example code below.

#include <iostream>

class x

{

private: // Members.

static int counter;

int data;

public: // Default constructor and destructor.

x():data(++counter){printf("Object %d created!\n",data);}

~x(){printf("Object %d destroyed!\n",data);}

// other members omitted for brevity...

};

// Initialise static counter.

int x::counter=0;

int main()

{

// Instantiate an array of 10 objects.

x arr[10];

// .. do some work with the array ..

return( 0 );

// The array falls from scope, destroying the objects.

}

Example output:

Object 1 created!

Object 2 created!

Object 3 created!

Object 4 created!

Object 5 created!

Object 6 created!

Object 7 created!

Object 8 created!

Object 9 created!

Object 10 created!

Object 10 destroyed!

Object 9 destroyed!

Object 8 destroyed!

Object 7 destroyed!

Object 6 destroyed!

Object 5 destroyed!

Object 4 destroyed!

Object 3 destroyed!

Object 2 destroyed!

Object 1 destroyed!

How do you write a program in c plus plus which accepts a number from the user and generate prime number till that number?

#include<iostream.h>

#include<conio.h>

#include<math.h>

void main()

{

int i,j;

clrscr();

for(i=3;i<=1000;i++)

{

for(j=2;j<=i;j++)

{

if(i%j==0)

break;

}

if(i==j)

cout<<j<<"\t";

}

getch();

}

//try it by apurba sinus

Calculate even numbers of nodes in link list in c plus plus?

The number of even nodes in any list is always half size of the list rounded down to the nearest integer. To round down you simply take the integral portion of the division. E.g., for a list of 5 nodes, nodes 2 and 4 are the even nodes, therefore there are only 2 even nodes. Thus: 5 / 2 = 2.5 = 2. A list of 4 nodes also has 2 even nodes, thus 4 / 2 = 2.0 = 2.

What is the difference between overloading and overriding and polymorphism in terms of C plus plus?

In C++, overloading, overriding, and polymorphism have the following meanings...

Overloading is when you create two functions of the same name, but with different argument types, or with a different number of arguments. The compiler generates code for each case. This can be done inside or outside a class. Operators can also be overloaded, as they are (for all practical purposes) functions, but operators can only be overloaded in the context of a class.

Overriding is when you derive a child class from a base class, and you replace a method (function) of the base class with a method of the child class using the same type and number of arguments. This is not overloading - it is redeclaration - and the overridden method only applies when dealing with an instance of the child class.

Polymorphism is the same as overriding, except that you declare any base method virtual, making all base and derived methods virtual. Virtual, in the context of a class, means to create a table in the static portion (all instances) of the class that point to the specific overridden variants of the methods of the class. This allows you to declare a pointer to the base class, initialize it with the address of an instance of either the base class or any of the child classes, invoke a method of the class, and have the proper binding determined at run-time.

Write a program to transpose of a matrix?

Program to find the Transpose of a Matrix

#include

#include

void main()

{

int i,j,n,t;

int m[5][5];

clrscr();

printf("Enter Order of Matrix : ");

scanf("%d",&n);

printf("Enter Elements of Matrix :\n\n");

for(i=0;i

{

for(j=0;j

{

scanf("%d",&m[i][j]);

}

}

printf("Transpose of the Matrix :\n\n");

for(i=0;i

{

for(j=i+1;j

{

t=m[i][j];

m[i][j]=m[j][i];

m[j][i]=t;

}

}

for(i=0;i

{

for(j=0;j

{

printf("\t%d",m[i][j]);

}

printf("\n");

}

getch();

}

Output:

Enter Order of Matrix : 3

Enter Elements of Matrix :

45 56 96

75 36 15

29 64 81

Transpose of the Matrix :

45 75 29

56 36 64

96 15 81

with out using temp variable:

#include

#include

void main()

{

int i,j,n,t;

int m[5][5];

clrscr();

printf("Enter Order of Matrix : ");

scanf("%d",&n);

printf("Enter Elements of Matrix :\n\n");

for(i=0;i

{

for(j=0;j

{

scanf("%d",&m[i][j]);

}

}

printf("Transpose of the Matrix :\n\n");

for(i=0;i

{

for(j=i+1;j

{

m[j][i]=(m[i][j]+m[j][i]-(m[i][j]=m[j][i]));

}

}

for(i=0;i

{

for(j=0;j

{

printf("\t%d",m[i][j]);

}

printf("\n");

}

getch();

}

What is the difference between data hidding and data abstraction?

Abstraction: Abstraction refers to removal/reduction of irrelevant data or unnecessary data or confidential data from a Class. Data hiding: Data hiding is a feature provided by the abstraction for hiding the data from the class.