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

Is it possible to immediately run a program without compiling it?

Not in C++, unless you have an interpreter. Most C++ development systems, however, are based on the compiler idiom, so, the answer is no.

However, Java is very close to C++, except for the platform and libraries, so one might consider Java to be an interpreter, however, you still must "compile" Java to byte code, so the answer is still no.

Write a c program that interchanges the odd and even elements of an array?

#include<stdio.h>

int main()

{

int num[]={1,2,3,4,5,6};

int i,temp;

for(i=0;i<=5;i=i+2)

{

temp=num[i];

num[i]=num[i+1];

num[i+1]=temp;

}

for(i=0;i<=5;i=i+2)

printf(''%d",num[i]);

return 0;

}

What does a plus b plus c plus f equals?

That's going to depend on the values of 'a', 'b', 'c', and 'f'.

What is operator overloading?

I think you mean operation overlord??? It is the American, Canadian and British offensive on Europe in World War 2. They landed in Normandy on 6th June 1944 (Commonly called D-Day, Day of Days or Deliverance Day) and progressed throughout France liberating Paris on the 25th August. This allowed the allies a foothold in Europe.

Class D is derived from class B The class D does not contain any data members of its own Does the class D require constructors?

Yes, D requires constructors, because all classes require constructors. However, whether you need to actually define them or not depends on whether B has any constructors other than a default constructor and a copy constructor. To understand why all classes must have constructors you need to understand how the compiler-generated constructors work.

All classes must have at least two constructors, one of which must be a copy constructor. If you do not define any constructors at all, the compiler automatically generates a default constructor (with no parameters) and a copy constructor. If you define any constructor, the compiler only generates the copy constructor unless you define your own. The compiler also generates an assignment operator and a destructor unless you provide your own.

In many cases the compiler-generated constructors will be sufficient for your needs thus there is no need to define your own in these cases. However, if your class contains one or more pointers to memory that is exclusive to each instance of a class (not shared amongst them), then you must provide your own constructors, as well as an assignment operator and a destructor, in order to manage that memory correctly. This is because the compiler-generated versions will treat all pointers as being pointers to shared memory and will simply copy their addresses, not what they contain. You must override this behaviour and ensure that those pointers are deep-copied; copying the memory itself, not just the address.

Constructors exist in order to initialise member variables. Even if your class has no member variables and therefore no real need for constructors, the compiler-generated constructors will still exist, as will the assignment operator and destructor, and it is important that you fully understand how these constructors work so that you will know exactly when you need to define your own and when you do not.

Consider the following example:

#include <iostream>

class B {

public:

B():m_data(0){ std::cout << "B::B()" << std::endl; }

B(const B& b):m_data(b.m_data){ std::cout << "B::B(const B&)" << std::endl; }

B& operator= (const B& b){ m_data = b.m_data; std::cout << "B::operator= (const B&)" << std::endl; return( *this ); }

virtual ~B(){ std::cout << "B::~B()" << std::endl; }

void SetData(const int i){m_data=i; std::cout << "B::m_data=" << m_data << std::endl; }

int GetData(){return m_data;}

private:

int m_data;

};

class D: public B {}; // no members or constructors defined.

int main()

{

D d1; // default constructor

std::cout << "d1.GetData()==" << d1.GetData() << std::endl;

d1.SetData( 100 );

std::cout << "d1.GetData()==" << d1.GetData() << std::endl;

D d2(d1); // copy constructor -- same as: D d2 = *d;

std::cout << "d2.GetData()==" << d2.GetData() << std::endl;

d1.SetData( 200 );

std::cout << "d1.GetData()==" << d1.GetData() << std::endl;

std::cout << "d2.GetData()==" << d2.GetData() << std::endl;

d2 = d1; // assignment operator

std::cout << "d2.GetData()==" << d2.GetData() << std::endl;

std::cout << std::endl;

return(0);

} // All objects fall from scope here.

Output:

B::B()

d1.GetData()==0

B::m_data=100

d1.GetData()==100

B::B(const B&)

d2.GetData()==100

B::m_data=200

d1.GetData()==200

d2.GetData()==100

B::operator= (const B&)

d2.GetData()==200

B::~B()

B::~B()

Since we provided no constructors in D it is difficult to see exactly what is going on here. In the main function we initially declare d1 to be of type D, but the first line of output is B::B(). Clearly the base class constructor is being invoked but it is not clear exactly how it was invoked. You'd be forgiven for thinking that since D inherits from B then it must inherit B's default constructor, but you cannot inherit constructors any more than you can inherit friends, operators or destructors from a base class. They are part of the interface but they are not part of the inheritable interface.

The answer, of course, lies in the fact the compiler has generated constructors for us behind the scenes. But since we don't have access to them we cannot trace them. So let's just clarify exactly what's going on by explicitly declaring constructors exactly as the compiler would have generated them for us. Let's also include some trace code so that we can see how they relate to the existing traces:

class D: public B {

public:

D():B(){ std::cout << "D::D()" << std::endl; }

D(const D& d):B(d){ std::cout << "D::D(const D&)" << std::endl; }

D& operator= (const D& d){ B::operator=( d ); std::cout << "D::operator= (const D&)" << std::endl; return( *this ); }

~D(){ std::cout << "D::~D()" << std::endl; }

};

Output:

B::B()

D::D()

d1.GetData()==0

B::m_data=100

d1.GetData()==100

B::B(const B&)

D::D(const D&)

d2.GetData()==100

B::m_data=200

d1.GetData()==200

d2.GetData()==100

B::operator= (const B&)

D::operator= (const D&)

d2.GetData()==200

D::~D()

B::~B()

D::~D()

B::~B()

Now things are somewhat clearer. Although B::B() looks like it was invoked before D::D(), they were actually invoked the other way around. Here's the default constructor for D:

D():B(){ std::cout << "D::D()" << std::endl; }

Note that before we enter the construction body (which contains the trace) we explicitly call the default constructor of B, hence it appears to be invoked first. However, this is, in fact, the correct order of events since we cannot construct an instance of D unless we first construct an instance of B. Only when B has been fully constructed can we then construct D.

Note also that even if we'd omitted the call to B() in the initialisation list, it would have been invoked automatically for us. That is, if we do not specify a base class constructor, the default constructor is invoked automatically. This fact is vital when it comes to declaring copy constructors:

D(const D& d):B(d){ std::cout << "D::D(const D&)" << std::endl; }

Here, we've called the base class copy constructor from the initialisation list: B(d). We have to do this because if we omit it, we'll end up calling the default constructor instead, which is not what we expect of a copy constructor. Here's the output trace snippet we'd have encountered had we omitted it:

d1.GetData()==100

B::B()

D::D(const D&)

d2.GetData()==0

Clearly, d2 cannot be a copy of d1 if their base class members differ, hence we must explicitly call the base class copy constructor (just as the compiler-generated copy constructor did).

Note that the assignment operator is not a constructor (it applies to existing objects only) and therefore does not have an initialisation list. However, the function body invokes the base class method, just as the compiler-generated version did.

The remainder of the output is fairly self-explanatory but note that destruction occurs in the reverse order of construction, thus D must be destroyed before B can be destroyed. Note also that since D is derived from B, B's constructor must be declared virtual. This is required because if we held a pointer to a derived class' base class and subsequently destroyed it, we would rightly expect the derived class' constructor to be invoked first. But if B's constructor were not virtual, we would end up destroying B alone, leaving an invalid instance of D in memory with no way to destroy it (a memory leak).

Explain a pure virtual function with an example?

There are no pure virtual functions, but there are pure virtual function calls.

In C++, classes can define abstract functions. Those are virtual functions for which no implementation is supplied in the class that defines it. Abstract functions are typically used to define a contract. For example, a base class for any vehicle might guarantee that a move() method exists, but only classes derived from vehicle implement this method according to the properties of the specific vehicle: a bike, a car, a skateboard, etc. Classes containing abstract functions are sometimes called abstract classes.

The C++ compiler does not allow the creation of an object of type vehicle in this example, because the vehicle class contains an abstract function.

Classes derived from vehicle (derived in first or higher degree) must supply an implementation of this method before the compiler allows the creation of an object of this type.

Therefore, any valid object descended from vehicle must have an implementation of the move method. However, since it is possible to create pointers to abstract classes (classes that contain abstract functions which have not yet been given an implementation), pure virtual function calls can occur at runtime.

Consider this example:

class vehicle {

public:

virtual void move(void) = 0; // abstract function

};

class motorizedVehicle : vehicle {

...

};

class car : motorizedVehicle {

public:

virtual void move(void) {

... // implementation

}

};

An application cannot create objects of type vehicle or motorizedVehicle, but it can create pointers to those. Those might give access to classes that have no implementation for the move method, and calling it results in a run-time diagnostic known as a pure virtual function call.

How inheritance helps in building class hierarchies in c plus plus?

Inheritance allows you to derive new objects from existing objects, thus allowing you to re-use the existing code (known as the generic code), augmenting or overriding that existing code in order to provide more specialised functionality (the specialised code).

For instance, if you have a Rectangle class, you might choose to derive a Square class from the Rectangle class. Thus the Square class inherits all the properties of a Rectangle (such as 4 vertices and 4 edges meeting at 90 degrees), but specialises the class to ensure that all four edges are always equal length. In other words, a Square is a more-specialised form of Rectangle, and therefore need only cater for the properties that are unique to Squares, whilst inheriting all the properties that are common to both Squares and Rectangles.

This is not unlike the real-world where you will often adapt an existing object to suit a new purpose, rather than build a new object completely from scratch, thus saving you a lot of time and money. In other words, we don't spend our time continually re-inventing wheels, we simply use an existing wheel and adapt it to suit our needs. The more closely the existing wheel resembles the wheel we actually want, the less work we have to do to adapt it.

Function of heatsink?

when your PC has been inoperation for a while the components inside start to heat up this heat can cause damage to those components a heat sink turns the heat into air and vents it out of the PC making sure your compnents eg processors are still in working order

What is abstract base class?

An abstract class is a class that cannot be directly instantiated. The purpose of such a class is to put some logic in a base class and force derived classes to implement the remaining functionality. Since the full functionality is only available in the derived class, the base class is declared as abstract so that it cannot be instantiated directly.

How many keywords in c plus plus now?

63 asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

How does friend operator function differ from member operator function?

In C++, we know that private members cannot be accessed from the outside class.

That is a non-member function cannot have an access to the private data of a class.

However there could be a situation where we would like two classes to share a particular function.

For example consider a case where two classes, manager and scientist have been defined.

We would like to use a function income_ tax () to operate on the objects of both these classes.

In such situation, C++ allows the common function to be made friendly with both the classes. Such a function needs not be member of any these classes.

To make outside function friendly to a class, we have to simply declare this function as a friend of a class as shown below:

Class ABC

{

……

…..

Public:

……..

……..

Friend void xyz (void); //declaration

};

When the function is logically coupled with the class (like your maze connectedness example)

When the function needs to access private or protected members, it's better to make it a member than a friend. when it's a generic function that can be templatized to naturally work on other classes (look at the header for good example) .

C plus plus programme to compare strings?

#include<iostream>

#include<string>

int compare (const std::string& a, const std::string& b)

{

int n=1;

std::string::const_iterator ai=a.begin(), bi=b.begin();

for (int n=1; ai!=a.end() && bi!=b.end(); ++ai, ++bi, ++n)

{

char ca = *ai;

char cb = *bi;

if (ca<cb) return n * (-1);

if (cb<ca) return n;

}

if (ai==a.end() && bi==b.end()) return 0;

if (ai==a.end()) return n * (-1);

return n;

}

int main()

{

std::cout

<< "When comparing strings, zero indicates the two strings are equal.\n"

<< "A negative value indicates the first string is less than the second string.\n"

<< "A positive value indicates the first string is greater than the second string.\n"

<< "The absolute value indicates the characters that differ in the strings. Thus\n"

<< "-10 or 10 indicate that the 10th characters show a difference.\n"

<< std::endl;

std::string x = "This is a string.";

std::string y = "This is another string.";

std::string z = "This is another.";

std::cout << "String x = "" << x << """ << std::endl;

std::cout << "String y = "" << y << """ << std::endl;

std::cout << "String z = "" << z << """ << std::endl;

std::cout << std::endl;

std::cout << "compare(x,x) = " << compare(x,x) << std::endl;

std::cout << "compare(x,y) = " << compare(x,y) << std::endl;

std::cout << "compare(x,z) = " << compare(x,z) << std::endl;

std::cout << "compare(y,x) = " << compare(y,x) << std::endl;

std::cout << "compare(y,y) = " << compare(y,y) << std::endl;

std::cout << "compare(y,z) = " << compare(y,z) << std::endl;

std::cout << "compare(z,x) = " << compare(z,x) << std::endl;

std::cout << "compare(z,y) = " << compare(z,y) << std::endl;

std::cout << "compare(z,z) = " << compare(z,z) << std::endl;

std::cout << std::endl;

}

Write a programme that calculates length and width of rectangle in c plus plus?

Commented code for a win32 console application:

#include //Include stdio.h for console input/output funcs

#include //Include conio.h for getch function (lol)

void main( )

{

int nWidth, nHeight; //Variables to hold width and height of rectangle

while( 1 ) //Infinite loop - can only be exited using "break;" (among others)

{

printf( "Enter rectangle width: " ); //Print text...

scanf( "%d", nWidth ); //Scan for user input

fflush( stdin ); //Flush user input

printf( "Enter rectangle height: " ); //Print text...

scanf( "%d", nHeight ); //Scan for user input

fflush( stdin ); //Flush user input

printf( "Area of rectangle with width of %d and height of %d is %d\n", nWidth, nHeight, nWidth*nHeight ); //Print text...

fflush( stdout ); //Flush output

//Now program will jump back to start of loop

}

}

Differentiate between overloading unary operator and overloading binary operator?

Unary operators declared as member function take NO arguments; if declared as global function, then take only one argument.

Binary operators declared as member functions take one argument; if declared as global function, then would take two arguments.

Note: The first argument for member function overloaded is always the class type; the class in which the operator is declared.

Is c plus plus is pure object oriented?

No. C is not object-oriented, it is a procedural language.

C++, while object-oriented, is not purelyobject-oriented. One of the requirements for a pure object-oriented language is that everything is an object. C++ still has primitive data types (int, long, double, etc.), and so is not purely object-oriented.

What are the different types of codes in c plus plus?

You can create an infinite type of classes in C++, memory permitting of course. Defining a class does not actually consume any memory, just as defining any user-defined type does not physically consume memory -- memory is only consumed when you instantiate an object of the class, just as instantiating a variable from a type consumes memory, not the type itself. However, you do need disk-space to store the files in which you declare your types, thus the number of unique types you can declare is ultimately determined by the amount of free storage space you have. Aside from that the only limit is your imagination and how you classify your objects (which is, after all, the whole point of declaring classes in the first place).

What do you mean by type conversion in c plus plus?

A no converting type cast is a type cast where the underlying data type is intrinsically the same as the type being cast, thus no conversion is required. This will often occur when explicitly converting from one type definition to another when both are in fact the same definition.

For instance, type casting from an unsigned int to a size_t is a no converting type cast because the size_t data type is merely a type definition (typedef) for an unsigned integral. Thus type casting between any of the following would result in a no converting type cast:

unsigned

unsigned int

unsigned long

unsigned long int

size_type

size_t

Note that unsigned and long are both modifiers, not types. If you omit the type, int is assumed, thus the first four are fundamentally unsigned int.

Note also that a conversion and a type cast are not really the same thing, but they do similar jobs. A conversion is an implicit conversion between types while a type cast is an explicit conversion between types. In other words, they're both conversions, but not all conversions are type casts.

This is best demonstrated with some examples:

int i = 3;

In the above example, the literal constant 3 is implicitly int, thus this is an example of a no conversion type cast (same fundamental type).

long j = long (i);

The above example is also a no converting type cast because int and long are fundamentally the same type. Remember, long is a modifier, not a type in its own right, thus long int is implied, and a long int is fundamentally the same as an int.

unsigned int k = i;

The above example is an implicit conversion because the value of i (3) is assigned to a fundamentally different type to that of i.

unsigned int l = (unsigned int) i;

unsigned int m = static_cast<unsigned int> (i);

The above examples are explicit conversions (type casts). Both explicitly cast the integral 3 to an unsigned int.

Explicit conversion (type casting) between primitive types is usually unnecessary because the compiler knows how to convert between these types and it's generally not something the programmer need overly concern themselves with. However, it can sometimes be important to highlight the fact that a conversion is taking place. In these cases it is best to be explicit and the static_cast operator is the best way of making the cast stand out. Conversion to or from more complex objects should be handled by the object's themselves through class conversion operators that implement static_cast where appropriate, and dynamic_cast or reinterpret_cast when the conversion is more complex. Again, it can be important to highlight the fact a conversion is taking place so it's best to keep conversion operators to the absolute minimum and force consumers to be explicit with their conversions. You can also use const_cast to highlight the fact that the constness of a type is being converted.

C plus plus program for linear search non-recursive method?

#include

#include

#include

void main(){

int arr[100],i,element,no;

clrscr();

printf("\nEnter the no of Elements: ");

scanf("%d", &no);

for(i=0;i

printf("\n Enter Element %d: ", i+1);

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

}

printf("\nEnter the element to be searched: ");

scanf("%d", &element);

for(i=0;i

if(arr[i] == element){

printf("\nElement found at position %d",i+1);

getch();

exit(1);

}

}

printf("\nElement not found");

getch();

}

Output:

Enter the no of Elements: 5

Enter Element 1: 12

Enter Element 2: 23

Enter Element 3: 52

Enter Element 4: 23

Enter Element 5: 10

Enter the element to be searched: 23

Element found at position 2

What is the difference between array of pointers and pointer to an array?

An array of pointers is that for eg if we have array of 10 int pointers ie int *a[10] then each element that which is stored in array are pointed by pointers. here we will have ten pointers. In pointer to an array for eg int(*a)[10] here all the elements that is all the ten elements are pointed by a single pointer.

What is the c plus plus program that finds max value in the array of size n?

#include

using std::cout;

using std::endl;

double maxValue(double arr, const intarrSize);

int main()

{

const int arrSize = 10;//Size of the array you are going to use

double arr[arrSize] = {0.0};

cout << endl << "Enter the array elements..."

for ( int i = 0; i < arrSize; i++ )

{

cout << endl << "Enter " << (i + 1) << " element:";

cin >> arr[i];

}

cout << endl << "Max value is: " << maxValue;

system("PAUSE");

return 0;

}

double maxValue(double arr, const intarrSize)

{

double max = arr[0];

for ( int j = 0; j < arrSize; j++ )

{

if ( max < arr[j])

{

max = arr[j];

}

}

return max;

}

Can you get a STD FROM snot?

If the seminal fluid is infected, even a microscopic amount of it can transmit disease.
None at all. All that is needed for a Sexually Transmitted Disease is close skin to skin or oral contact. Particularly more so when it invoves the genital areas. Penetration or ejaculation are not necessary for the transmission of many STD.

When do preprocessor directives execute in c plus plus?

Preprocessing is the first stage of compilation, where macros are expanded, conditional compilation established and code replaced according to the specified directives. The resulting code produces intermediate source files which are then compiled by the main compilation process. Your IDE may include options to retain these intermediate files so you may examine them.

What are the differences between a struct data type and a class data type in c plus plus?

A struct declares all members public by default, whereas a class declares all members private by default. That is really the only difference. Structs are from C and classes from C++, you can use both structs and classes in C++ but only structs in C.

Trending Questions
Can c plus plus run on windows? What do you mean by default arguments. How do you delare them? How do you instantiate an object in OOP? How do you write the programme that display truth table of AND gate by using C or C plus plus programming language? Who created c and c plus plus and java? A method that is automatically called when an instance of a class is created? How do you write a C plus plus function lastLargestIndex that returns the index of the last occurrence of the largest element in the array? What value of c makes the polynomial below a perfect square trinomial x2-14x plus c? How operator overloading is useful in class based programming? How do you write je vais un sandwich using aller plus infinitive? Find vowel from given string in C plus plus language? Implement a base class Geo and derived from this class Rect a constraint such as any derived classes from Geo must have method to calculate the area.Derive from Rect class Sqr its const take one value? Code for changing background color in C plus plus? Write a c program to compare two strings without using builtin function? C program to accept name age and print eligible for vote or not? Why you use integer variables when the value of float and integer is same? How will you declare an array of three functions pointer where each function receives two ints and returns a float? What is a C plus plus program to demonstrate the use of access specifiers? When is a friend function compulsory? Write a program to concatenate two strings in C plus plus?