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

What is a logical operator in c plus plus?

The boolean and operator in C and C++ is &&

a < 3 && b > 4 // relational

The bitwise and operator in C and C++ is &

maskresult = maskinput & maskvalue // bitwise

What is the best C plus plus compiler?

If you mean which is the most standards-compliant then Clang would have to come out on top, closely followed by GCC. MSVC++ is fine if all you do is program in Windows, but its lack of compliance means it is not really C++ -- it's a Microsoft-specific implementation of C++.

How are an objects instance variables initialized of a class has only a default constructor?

You have to explicitly initialise all instance variables, otherwise their values will be initialised to whatever happens to be in memory at the time they are instantiated.

Consider the following class which has no explicit initialisation:

#include <iostream>

class object

{

public:

object(){}

public:

const int getData( void ) const { return( m_data ); }

private:

int m_data;

};

int main()

{

object O;

printf( "O.m_data = %d\n", O.getData() );

return( 0 );

}

Example output:

O.m_data = -858993460

This is not particularly useful; we must ensure m_data is initialised before we access its value.

One way to initialise object::m_data is from within the body of the constructor:

object(){ m_data = 0; } // inefficient initialisation

However this is quite inefficient because object::m_data will have already be instantiated by the time we got to the constructor body. This is akin to the following C-style initialisation:

int x; // instantiate x

x = 0; // initialise x

When what we really want to do is:

int x = 0;

Or use the more formal construction semantics:

int x(0);

Both achieve the same thing. They both initialise the variable x at the point of instantiation, not after instantiation. Fortunately, C++ allows us to initialise all instance variables at the point of instantiation, via the constructor's initialisation section:

object():m_data(0){} // efficient initialisation

While initialising a single primitive data type in the constructor body isn't going to cause major problems in terms of efficiency, with more complex data types the inefficiencies can very quickly add up. Thus it is important to use the initialisation section as much as possible and to only use the body of the constructor when there is no option.

The initialisation section is particularly important when dealing with derived classes. Consider the following:

#include <iostream>

class base

{

public:

base():m_int(0){}

base(const base& object):m_int(object.m_int){}

public:

const int getInt( void ) const { return( m_int ); }

void setInt( const int data ) { m_int = data; }

private:

int m_int;

};

class derived : public base

{

public:

derived():m_float(0.0){}

derived(const derived& object):m_float(object.m_float){}

public:

const float getFloat( void ) const { return( m_float ); }

void setFloat( const float data ) { m_float = data; }

private:

float m_float;

};

int main()

{

derived d;

d.setInt( 1 );

d.setFloat( 2.0 );

printf( "d.getInt() = %d, d.getFloat() = %f\n", d.getInt(), d.getFloat() );

derived c(d); // call copy constructor.

printf( "c.getInt() = %d, c.getFloat() = %f\n", c.getInt(), c.getFloat() );

return( 0 );

}

Example output:

d.getInt() = 1, d.getFloat() = 2.000000

c.getInt() = 0, c.getFloat() = 2.000000

Note that c should be an exact copy of d, but there's clearly a difference in the integer variables inherited from the base class. This is because the derived class copy constructor called the base class default constructor, not the base class copy constructor as you might have expected. To resolve this we must explicitly call the base class copy constructor and the only way to do so is via the initialisation section of the derived class:

derived(const derived& object):base(object),m_float(object.m_float){}

Note that the derived class' copy constructor now includes a call to base(object) in the initialisation section. This ensures the base class copy constructor is called. Although object is actually an instance of derived, because it derived from base it is also a kind of base, thus the call is legitimate. Now if we run the code we'll get the expected result:

d.getInt() = 1, d.getFloat() = 2.000000

c.getInt() = 1, c.getFloat() = 2.000000

As your classes become more and more complex you will inevitably find yourself creating overloaded constructors to provide a wide variety of initialisation methods. But keep in mind that it costs absolutely nothing to use the initialisation sections even if several constructors end up using the exact same initialisations. And while it is tempting to move all of the common initialisation code into a private method of the class and have each constructor call that method (known as a construction helper function), this simply adds yet more inefficiency by introducing yet another unnecessary function call. Helper functions such as these are undoubtedly useful during the initial development of a class but as soon as the class is finalised, get rid of the helper function and move all that functionality into the initialisation sections where they belong. In the case of derived classes, base class constructors will be called whether you like it or not, so it makes sense to call the most appropriate base class constructor from within the initialisation section of each of your derived class constructors. Remember that if you do not specify a base class constructor, its default constructor will be called implicitly, which may or may not be the most appropriate constructor in all cases (not least in the case of the copy constructor).

What is reference variable in c plus plus?

A reference is not a variable of any kind. A reference is simply an alias; an alternate name for an object that already exists. It is analogous to a person with the birth name Robert who might also be known as Robbie, Rob, Rab, Bob and so on. They are all aliases for the same person, so every operation we perform on Bob or Robbie is actually performed on Robert.

Once we assign an object to a reference, we cannot subsequently assign another object to that same reference. Thus a reference is always guaranteed to refer to the same object for as long as that reference remains in scope. Moreover, a reference can never be null; it must always refer to something. As such, references must be assigned to an object at the point of declaration, just as you would a constant.

Note that although a reference is not a variable, the object it refers to can be, unless the reference itself is explicitly declared constant. By the same token, a non-constant reference cannot refer to a constant object.

References are typically used whenever we need to pass an object to a function by reference rather than the usual by value semantics. Like so:

void by_value (int x) {}

void by_reference (int& y) {}

In the above examples, x is a copy of the object we pass to the function, so any changes made to x will not affect the object we passed. However, y is a reference thus any changes made to the object referred to by y will be reflected in the object we passed.

A pointer variable is also a type of reference, but it behaves quite differently. Firstly, a pointer variable really is a variable; it is used to store a memory address thus it requires memory of its own. Secondly, unless the pointer is declared constant, we can change the address a pointer refers to by changing its value. Finally, a pointer may be null.

References are generally much easier to work with and more intuitive than pointers. For instance, we do not need to dereference a reference, thus we can use the member-of operator (.) rather than the pointer-to-member operator (->) when working with object references. Moreover, given that a reference can never be null, there is no need to test for null as we would with a pointer. When passing an object by reference, the function can simply use the reference, safe in the knowledge the reference refers to a valid object. If we pass a pointer, we lose that guarantee and must test the pointer before attempting to dereference it. Nevertheless, there can often be cases where passing an object to a function is optional, in which case we use a pointer argument defaulting to null.

There is also one other type of reference known as an r-value reference. An r-value is an operand that appears on the right-hand-side of an operator. Typically, an r-value is a constant since we would normally expect to only modify the left-hand-operand (the l-value). However, since C++11, move semantics require that an r-value be modifiable. For that reason we use r-value references.

We typically use r-value references when declaring move constructors and move assignment operators, like so:

struct S {

S (const S&); // copy constructor

S& operator= (const S&) // copy assignment

S (S&&); // move constructor

S& operator= (S&&) // move assignment

}

Note that S& is a reference while S&& is an r-value reference. The reason we need an r-value reference is that r-values that are moved are always assumed to be objects that will shortly fall from scope (such as when return an object by value). Thus move semantics must leave the r-value in an unspecified but valid state in order to allow the object to be destroyed. To achieve that, the r-value must be modifiable, hence we use an r-value reference.

The classic scenario is when moving a vector. Copying vectors is highly inefficient, but moving them is simply a case of switching ownership of the resource being moved; the array itself. Once the l-value has taken ownership of the resource, the r-value can simply be switched to an empty state. Note that we don't actually clear the vector (the resource no longer belongs to the r-value) we simply change its internal to state to reflect that of an empty vector. The vector can then be allowed to safely fall from scope.

It should be noted that the C++ compiler may well implement references as constant pointers and r-value references as pointer variables, however that is a matter of concern only to compiler designers. When programming in C++, it is vital that we understand that a pointer is a type while a reference is a programming tool.

How do you write a program in c plus plus that implements the n-queens problem with backtracking?

#include<stdio.h>

#include<conio.h>

#include<math.h>

int a[30],count=0;

int place(int pos)

{

int i;

for(i=1;i<pos;i++)

{

if((a[i]==a[pos])((abs(a[i]-a[pos])==abs(i-pos))))

return 0;

}

return 1;

}

void print_sol(int n)

{

int i,j;

count++;

printf("\n\nSolution #%d:\n",count);

for(i=1;i<=n;i++)

{

for(j=1;j<=n;j++)

{

if(a[i]==j)

printf("Q\t");

else

printf("*\t");

}

printf("\n");

}

}

void queen(int n)

{

int k=1;

a[k]=0;

while(k!=0)

{

a[k]=a[k]+1;

while((a[k]<=n)&&!place(k))

a[k]++;

if(a[k]<=n)

{

if(k==n)

print_sol(n);

else

{

k++;

a[k]=0;

}

}

else

k--;

}

}

void main()

{

int i,n;

clrscr();

printf("Enter the number of Queens\n");

scanf("%d",&n);

queen(n);

printf("\nTotal solutions=%d",count);

getch();

}

What are the merits of volatile in c plus plus?

The volatile specifier informs the compiler that an object could be modified by something that is external to the thread of execution; something that is not part of the program. For instance, when reading a hardware clock, you would rightly expect the value of that clock to change from one read to the next. But from the compiler's perspective, the clock remains constant because your code does not alter it between reads and is unaware of any external code that controls its value. Therefore the compiler will (rightly) optimise away what it believes to be redundant read operations which could easily break the semantics of your code.

By declaring an object volatile (even a constant object), you inform the compiler that the object may change between successive read or write operations and that all redundancy optimisations must not be applied to any code that uses that object.

Although often used as a method of synchronisation between concurrent threads within the same thread of execution that share the same object, you must not use it for this purpose. C++ provides very specific mechanisms for this purpose, such as an atomic, a mutex or a condition_variable. The volatile specifier must only be used when writing low-level code that deals directly with hardware, such as when writing device driver and embedded system software.

What is the difference between actual and formal argument in c plus plus?

Formal parameters are the parameters as they are known in the function definition. Actual parameters (also known as arguments) are what are passed by the caller. For example, in the following code, a and b are the formal parameters, and x and y are the actual parameters:

int max(int a, int b) {
if (a > b) return a;
else return b;
}

int m = max(x, y);

What are the advantages and disadvantages of DLL over single linked list?

The main advantage of a doubly-linked list is that you can traverse and search the list both forwards and backwards. Although you can also add to the beginning and end of the list, and retrieve the same, in constant time O(1), this is also possible with a slightly modified singly-linked list simply by maintaining a pointer to the last node as well as the first.

Thus the only real difference is whether you need to traverse bi-directionally or not. If not, a modified singly-linked list would be more efficient. And if you only require fast access to the first node, a standard singly-linked list would be slightly more efficient.

Disadvantages of multiple inheritance?

If a single class inherits from two other classes, each of which has the same function implemented, how can we tell which one to call? This ambiguity often leads to non-deterministic behavior of classes in multiple inheritance languages.

Why do you need to use comments in a C program?

Preferably as little as possible, however it depends on the language. Low-level languages require a vast amount of user-comments because it can be extremely difficult to read the logic from the code alone. High-level languages require very few comments because the code should be largely self-documenting. Languages like C++ allow you to express concepts and ideas directly in code, so there's very little you need to document with a comment. Choosing good names for functions, classes and variables is a vital aspect of creating readable code.

Why the concept of inheritance was introduced in OOP?

In object-oriented programming, inheritance allows the creation of is-a relationships. For example, a car is a vehicle, and a bike is a vehicle, so those could be modeled through a vehicle class, and a pair of car and bike classes, both derived from (inheriting from) the vehicle class. Derived classes like car and bike share common vehicle properties, such as speed, location, direction, number of wheels, etc.

What is a pointer variable in C?

Pointer variables point to data variables. They are mostly used to point to dynamically allocated data variables, but can actually point to anything (e.g. statically allocated variables, array elements, anywhere inside a variable, program machine code, I/O device descriptors, nonexistent memory). Misuse of pointer variables, either unintentionally or intentionally, is a major cause of nearly impossible to debug software problems in programs written in C (and C++).

What is a public class?

A public class is a base class declared with public inheritance:

class base {

// ...

};

class derived : public base {

// ...

};

In the above example, base is a public class of derived, thus derived is regarded as being a type of base. The derived class inherits all the public and protected methods of its base. Protected methods are accessible to the derived class, its derivatives and their friends.

If base were declared protected, its public methods become protected methods of derived. The base class is then an implementation detail of derived; only members of derived, its derivatives and their friends can treat derived as being a type of base.

If declared private, the public and protected methods of base become private methods of derived. The base class is then an implementation detail of derived; only members of derived and its friends can treat derived as a type of base.

Can you give a C plus plus program about FCFS algorithm?

#include<iostream.h>

#include<conio.h>

#include<alloc.h>

#include<stdio.h>

struct node

{

char name[10];

int bt;

int wt;

int tat;

struct node*next;

};

typedef struct node n;

n *start=NULL;

void main()

{

int i,m;

n *p,*temp,*t;

clrscr();

cout<<"\nEnter the number of Process:";

cin>>m;

for(i=0;i<m;i++)

{

p=(n*)malloc(sizeof (n));

cout<<"\n\tEnter the Process Name:";

cin>>p->name;

cout<<"\n\tEnter the Burst Time:";

cin>>p->bt;

if(start==NULL)

{

start=p;

start->next=NULL;

start->wt=0;

start->tat=start->bt;

}

else

{

temp=start;

while(temp!=NULL)

{

t=temp;

temp=temp->next;

}

t->next=p;

temp=p;

temp->wt=t->tat;

temp->tat=t->tat+temp->bt;

temp->next=NULL;

}

}

temp=start;

cout<<"\nProcesses\t\tBT\t\tWT\t\tTAT";

while(temp!=NULL)

{

cout<<"\n\t"<<temp->name;

cout<<"\t\t"<<temp->bt;

cout<<"\t\t"<<temp->wt;

cout<<"\t\t"<<temp->tat;

temp=temp->next;

}

cout<<"\n\n Created By:\n\tSanjog";

getch();

}

What is the latest compiler of C plus plus compiler?

C++ compilers are many and varied. There is no single "latest compiler" because every IDE implements their own version according to the current C++ standard. However some (Microsoft in particular) do not fully adhere to the C++ standard.

The "latest compiler" for your IDE is either provided as an interim update to the IDE, or by upgrading the IDE to the latest version.

Is a c plus good or bad?

Basically both are good at their places, can't be interchanged. But Java is best if we compare both because Java is much more secure, robust and portable as compared to C++ as a Java program is first converted to byte code and then interpreted. Also C++ program is compiled all at once but Java program is interpreted one instruction at a time thus making it more secure .

Program that input ten names from user c plus plus?

#include<iostream>

#include<vector>

#include<string>

int main()

{

std::vector<std::string> names;

for (int loop=0; loop!=10;)

{

std::cout << ++loop << " enter a name: ";

std::string name;

std::cin >> name;

names.push_back (name);

}

}

What is the difference between protected and friend in c plus plus?

The private, protected and public keywords are used to modify the access specifiers of class or struct members. Unless otherwise specified, class members are private by default, while struct members are public by default.

Private members of a class are only accessible to members and to friends of that class. Protected members are the same as private members, but are also accessible to derived classes. Public members have unrestricted access.

The private, protected and public access specifiers can also be used to modify the type of inheritance that applies to a derived class. Private inheritance means all public and protected members of the base class become private members of the derived class. Protected inheritance means all public members of the base class become protected members of the derived class. Public inheritance means all public and protected members of the base class remain public and protected members of the derived class. Private members of the base class are never inherited by derived classes. A derived class or one or more of its member functions may be declared a friend of the base class, thus permitting private access, but you would never do this unless the hierarchy were a closed, static hierarchy where all derivatives can be determined at compile time. Dynamically bound derivatives of unknown origin cannot be declared friends.

Can you have virtual constructor in cpp?

A virtual function is a method defined and implemented in a base class that we are expected to override in our derived classes.

When we derive a class from a base class, we automatically inherit all the public and protected members of the base class, but we are free to override any and all the methods, including private methods (we can even change the access type if we wish).

However, when we override a method in the base class, we can only call that override when we actually have a reference or pointer to the derived class itself. If we cast the reference or pointer to the base class we will end up calling the base class method. This is expected behaviour and is normally fine, but what happens if we have a pointer to a base class but we actually want to call the derived class method? This is particularly important when that call comes from the base class itself. How will it determine its actual type and make the correct call?

We could use runtime information within the base class to determine the actual type, but this would break a fundamental rule of encapsulation: a base class should NEVER be concerned about the inner workings of any of its derived classes. If we allow this, we'd be forced to update the base class every time we derived a new class from it. Apart from the performance penalty incurred with accessing runtime information, maintaining the base class code will quickly become unmanageable.

That is where virtual functions come in. Even though we are pointing at a base class, when we call a virtual function we actually call the derived class method instead. This is extremely powerful: we are no longer concerned with the actual type of object any more. We can treat the base class as if it were a generic data type, and the compiler will know exactly which version of a function to call regardless of whether the call was made from the base class or not.

But what if we want to call the base class method? Simple: make an explicit call to it. We don't need runtime information for this since every derived class is also a base class as well. The only exception is when the virtual function is declared private in the base class. In this case, we are not expected to call the base class method at all (only the base class and friends of the base class can make an explicit call to its private methods).

How to Change lower case to upper case in C plus plus?

Char 'a' is 97 decimal (61 hex) while char 'A' is 65 decimal (41 hex), a difference of 32 decimal (20 hex). Therefore test each char value in the char array (or string) using a for loop. If the char value is in the range 'a' to 'z', then subtract 32 decimal (20 hex).

The following example demonstrates the method:

void toupper(char* str, int len)

{

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

{

if(str[i]>='a' && str[i]<='z') str[i]-=32;

}

}

To convert from upper to lower case, use the following instead:

void tolower(char* str, int len)

{

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

{

if(str[i]>='A' && str[i]<='Z') str[i]+=32;

}

}

When using CodeBlocks IDE for Linux how do you compile the program you are writing as an EXE?

CodeBlocks is an extensible, cross-platform IDE but it does not come with a compiler nor a linker since they are platform-specific. When you first run the IDE, it will scan your system for all supported compilers and integrate them into your IDE If you have more than one supported compiler, then you must choose the master compiler. But if you have no compiler, then you must add one. To build an EXE you must configure the project's compiler and linker switches according to your chosen compiler. Consult the compiler's own documentation for more information on this.

C plus plus program to implement circular queue using doubly linked list?

#include<iostream.h>

class node

{

public:

int data;

node* link;

};

class queue

{

node* front;

node* back;

public:

queue()

{

front=NULL;

back=NULL;

}

void enqueue(int d)

{

node* ptr;

ptr=new node;

ptr->data=d;

ptr->link=NULL;

if(front==NULL)

{

front=ptr;

back=ptr;

}

else

{

back->link=ptr;

back=back->link;

}

}

void dequeue()

{

node* ptr;

ptr=front;

if(front==NULL)

cout<<"\n Nothing can be deleted. \n";

else

{

ptr=front;

front=front->link;

delete ptr;

ptr=NULL;

cout<<"\n The first element has been deleted.\n";

Front();

}

}

void If_Empty()

{

if(front==NULL)

cout<<"\n The queue is empty.\n ";

}

void Front()

{

if(front!=NULL)

cout<<"\n The first element is "<<front->data<<endl;

}

};

void main()

{

queue q;

int data;

char opt;

do

{

cout<<" Enter your data:\t";

cin>>data;

q.enqueue(data);

cout<<"\n Do you want to continue:\t";

cin>>opt;

}while(opt=='y'opt=='Y');

q.Front();

q.dequeue();

q.If_Empty();

q.dequeue();

q.dequeue();

q.If_Empty();

q.dequeue();

}

What is the purpose of a function in C plus plus?

The purpose of C++ is to produce machine code programs from a text-based source. While much of what you can do in C++ you can also do in C, the addition of object-oriented programming (OOP) in C++ makes it possible to model highly complex structures more easily than with C alone. OOP adds a much greater degree of abstraction but C++ still retains the low-level features of C, allowing programmers the freedom to use the tools that best suit the task at hand. While modern OOP languages such as Java are ideally suited to rapid-application development, they simply cannot compete with C++ in terms of efficiency and performance. Hence all major software developments, particularly operating systems, drivers, games and office applications are still programmed in C++ to this day.

Mid point algorithm for ellipse?

Midpoint Ellipse Algorithm

Midpoint ellipse algorithm is a method for drawing ellipses in computer graphics.

This method is modified from Bresenham's algorithm. The advantage of this modified

method is that only addition operations are required in the program loops. This leads

to simple and fast implementation in all processors.

Let us consider one quarter of an ellipse. The curve is divided into two regions. In

region I, the slope on the curve is greater than -1 while in region II less than -1.

dy/dx = -1

Region II

Region I

a

b

x

y

m = -1

Consider the general equation of an ellipse,

b2x2 + a2y2 - a2b2 = 0

where a is the horizontal radius and b is the vertical radius, we can define an function

f(x,y) by which the error due to a prediction coordinate (x,y) can be obtained. The

appropriate pixels can be selected according to the error so that the required ellipse is

formed. The error can be confined within half a pixel.

Set f(x,y) = b2x2 + a2y2 - a2b2

In region I (dy/dx > -1),

(xk, yk)

Prediction

(xk+1, yk-½)

SE

E

Region I

x is always incremented in each step, i.e. xk+1 = xk + 1.

yk+1 = yk if E is selected, or yk+1 = yk - 1 if SE is selected.

In order to make decision between S and SE, a prediction (xk+1, yk-½) is set at the

middle between the two candidate pixels. A prediction function Pk can be defined as

follows:

What are the Advantages of linked list over stack and queue?

A linked list is a data structure in which each node has a pointer to the next node, and thus the whole list is linked.

Some advantages are:

* Easy traversal of the whole list (simply follow the pointers) * Easy insertion and deletion of nodes (don't need to move all the other nodes around)