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 punctuation ends most lines of C and C plus plus code?

C programs are composed from data types and functions. Functions are composed from one or more statements. A statement is composed from one or more expressions terminated by a semi-colon. A semi-colon without an expression is itself a statement (an empty statement).

Every C program must have at least one function, the global main function. This serves as the entry-point of the application. When we return from the main function, the program terminates normally.

The C standard requires that the global main function return an integer to the execution environment, where the value 0 is conventionally used to indicate "no error". As such, the minimum C program is as follows:

int main (void) {

return 0;

}

What is function calling in c plus plus?

Function calling is where your code branches off to execute a function and then returns to the instruction following the call. The function may also return a value that can be stored and/or processed by the code that called it. Functions allow common code to be separated from the code that uses the common code, thus reducing maintenance (the code in the function is written once, rather than every time it is required).

How can you use abstract classes instead of interfaces?

In most cases, you will want to use abstract classes IN ADDITION to interfaces.

You should use an abstract class in the following circumstance:

  1. the abstract class is clearly part of class hierarchy, and does not just describe some sort of basic functionality. Specifically, abstract classes are a good idea where they will be directly inherited from to create a concrete concept, but the abstract class itself is too indistinct to have any specific instance of it created.
  2. You want to provide an implementation for a set of methods that will be reused by a significant number of other classes, all of which can be fit into a class hierarchy.

In practice, abstract classes are a good way to collect common code into one place, to make maintenance easier.

For instance, say you have a class and interface structure like this:

Class A

Interface X

Class B extends A implements X

Class C extends A implements X

Both B and C will have the all the methods declared in X; if the implementation of those methods is the same (or can be made the same), then X is a good candidate for changing to an abstract method:

Class A

Abstract Class X extends A

Class B extends X

Class C extends X

Thus, you have removed the code duplication that was happening when using interfaces.

Note that doing the above is NOT a good idea if any class which implement interface X cannot be made a subclass of the new abstract class X.

What is the difference between a null pointer and a null macro?

Using a NULL macro to make C portable

I'll assume that you're asking your question for C type language programming. A NULL pointer is a pointer that's guarnteed to point to nothing. This may be 0 in a UNIX/Linux system or some other address in another system. Using the NULL macro to set/initialize your pointers will make your programs more portable among systems than using something like the 0.

#include

char *c = 0; // initialize to NULL--not portable
char *p = NULL; // initialize to NULL as defined in stdio is portable


AddendumThe code:

char *c = 0;

actually is portable because the compiler converts 0's used in a pointer context (cast to a pointer) to the machine's representation of a NULL pointer, which may or may not be all 0 bits. The NULL macro itself might be defined as something like 0 or (void *)0, and both definitions are portable. As a corollary, the following code is also portable:

if (!c) {
// do something
}

because it is equivalent to:

if (c != 0) {
// do something
}

and the 0 above is converted to a NULL pointer because it is being compared with a pointer.

How do you write a programme that prints the sum of all the multiples of 3 or 5 below 1000 in c plus plus?

First work out the algorithm for what you want to do and then encode that using the C++ language.

Alternative Answer

In this case, the algorithm will consist of a loop that counts from 1 to 1000, testing each value to see if it can be divided by 3 or 5 without leaving a remainder. If so, it gets added to a running total. When the loop ends, the running total is the final answer.

To determine a remainder in C++, we use the modulo operator (%). That is; 9%5 is 4 because 9 divided by 5 is 1 remainder 4, whereas 9%3 is zero. Therefore if either operation evaluates to zero, the value can be added to the running total.

int DoSum( void )

{

int total=0;

for(int x=1; x<1000; ++x)

if( !(x%3) !(x%5) )

total+=x;

return(total);

}

An alternative (and more efficient) algorithm will perform the same loop twice, first in steps of 3 and then in steps of 5. Since we're no longer testing for invalid values, we simply sum every value.

int DoSum( void )

{

int total=0;

for(int y=0; y<2; ++y)

{

int step=y?5:3; // if y is 0, step is 3, otherwise step is 5

for(int x=step; x<1000; x+=step)

total+=x;

}

return(total);

}

What is the purpose of a C plus plus constructor?

The constructor in C++ is a function that runs when an object is created. It is used to initialize the object.

Types of constructors include default constructors (no arguments), copy constructor (one argument of same type as object), conversion constructors (one argument of some other type), and other constructors (all other cases).

If you do not provide a default constructor, the object will not be initialized.

If you do not provide a copy constructor, the compiler will blindly copy the attributes of the old object into the new object whenever a copy is made, such as in a function call with the object as an argument. This may or may not be safe, especially if any of the attributes are pointers, because that creates the situation of two pointers to the same region of memory. In that case, if that region of memory is an object, then when the object is destroyed, so will the pointed to object, and that will leave the original copied object in an invalid state, with its pointers referencing deleted memory.

Write a program in c plus plus to display the palindrome numbers between 10 and 1000?

#include<iostream>

unsigned int reverse(unsigned int num, unsigned int base=10)

{

unsigned int rev=0;

while( num )

{

rev*=base;

rev+=num%base;

num/=base;

}

return( rev );

}

int main()

{

std::cout<<"Palindromic numbers from 10 to 1000\n"<<std::endl;

for( unsigned int num=10; num<=1000; ++num)

if( num==reverse(num))

std::cout<<num<<std::endl;

}

An algorithm to Reversing the order of elements on stack S using 1 additional stacks?

// stack to contain content

Stack sourceStack = new Stack();

// ... fill sourceStack with content

// stack to contain reversed content

Stack targetStack = new Stack();

while (!sourceStack.empty())

{

targetStack.push(sourceStack.pop());

}

// targetStack contains the reversed content of sourceStack

Why do we need constructor?

when the object is instantiated(created) and delared,it has to assigned with variables.constructor is used for this purpose. syntax: classname ojbectname=new classname(); here classname() is a constructor. eg: box bb=new box(5,10); when this object is instantiated,it can be directly accessed by the constructor(similar to method but without a void because the instance variables are directly used) box(5,10) { }

What is c plus plus data type?

The C++ string classes are derived from the std::basic_string<T> template class, where T is a character type. The standard provides the two most common string types, std::string (std::basic_string<char>) and std::wstring (std::basic_string<wchar_t>). The former is used for ASCII strings (which includes UTF-8 strings) while the latter is used for wide-character strings, particularly UNICODE strings.

All standard library strings are represented by an array of some character type (such as char or wchar_t) however, unlike an ordinary array, the individual character elements cannot be re-ordered other by overwriting each character. If you simply need an array of characters that can be re-ordered then use a std::vector<char> or std::vector<wchar_t> rather than a string.

The standard library strings include a rich set of methods, operations and algorithms that are commonly used with strings, such as std::string::find() to locate a character within a string, std::string::substr() to extract a substring from a string, and operator+= to concatenate one string onto another. Most implementations include the short string optimisation so that short strings (up to around 14 characters or so) may be stored in local memory rather than on the heap. Many strings tend to be short so this can provide enormous performance benefits with little cost in terms of memory.

Draw a flowchart to accept 2 numbers and check if the first is divisible by the second?

Drawing flowcharts is impossible in a text-based forum. So here's the pseudocode instead:

  1. input x
  2. input y
  3. if(x%y==0) then print "x is divisible by y" else print "x is not divisible by y"

Note that line 3 divides x by y and if the remainder is 0 then x is divisible by y, otherwise it is not.

Example of encapsulation and abstraction in an object oriented programming language?

Encapsulation example:

Ink is the important component in pen but it is hiding by some other material.

Abstraction example: ATM is a good example of abstraction, we doesn't know what are all the internal processes that are going when we access it..instead we know only the inquiries, deposit, withdrawl etc...

Explain why a class might provide a set method and a get method for an instance variable?

A class might provide a set method (setter) and a get method (getter) for an instance variable in order to encapsulate the internal implementation of the class, and to isolate that implementation from the public interface of the class.

Even if the setter and getter does no more than directly set and get the instance variable, the public interface should use that paradigm in order to allow for possible future alteration of the implementation, while minimizing the impact of doing so.

Proper OOD/P (Object Oriented Design/Programming) should always make the implementation be private, even for derived classes. This reduces error, and reduces "lazy" coding techniques.

How do you make a function repeat itself in C plus plus?

There are three ways to do repetitions in C as far as I know. The first is to use recursion (a function which calls itself) the second being a for loop and the third being a while loop, though both of these are basically the same thing. Here's a demonstration of using these three methods to compute the x raised to the power of y: (note this isn't the most efficient way of calculating the power of a number but it's good enough for an example)

//Recursion:

int pow(int base, int pwr){

if(pwr == 0){

return 1;

}else{

return base * pow(base, pwr - 1);

}

}

//For loop

int pow(int base, int pwr){

int i;

int result = 1;

//The for loop initialises i to the value of pwr, then

//runs the loop, subtracting 1 from i each time until

//i fails the test (i > 0) at which point the loop finishes

for(i = pwr; i > 0; i--){

result *= base

}

return result;

}

//While loop

int pow(int base, int pwr){

int result = 1;

while(pwr > 0){

result *= base;

pwr--;

}

return result;

}

How do you instantiate an object in OOP?

In most OOP languages, you use the "new" keyword to indicate that you wish to create an object of a given class. Often, that construct will look as follows:

PlayerCharacter pc = new PlayerCharacter("Jane Doe");

The first PlayerCharacter is the "data type" for the variable "pc". Equals ("=") assigns the right-hand value to the left-hand value (pc). The new keyword indicates that you wish to allocate memory for an object and call a constructor. The second PlayerCharacter calls the constructor for the PlayerCharacter class, which expects a single string for the player character's name (presumably).

Disadvantages of template in c plus plus?

When used correctly and for the purpose intended there are no disadvantages to templates. Templates are type-safe, can be debugged by the compiler and make it easier to write functions and classes that operate upon a type without the need to write duplicate code by hand. If you're using templates for any other purpose then there will obviously be disadvantages. However, when you consider the alternatives, macros are disadvantageous because they are not type-safe, cannot be debugged by the compiler and are always inline expanded (which is not always a good thing), while coding by hand is disadvantageous because it introduces duplicate code and increases the maintenance cost of that code. All three methods have their uses, but when used incorrectly you will always find disadvantages. That is not the fault of the methods themselves, that is the fault of the programmer.

What are the parts of an array?

Its type, name and number of elements.

char example[12]; // a char array, named 'example' with 12 elements.

The name is also a reference to the array itself, referring to the first element in the array (e.g., example == &example[0]).

When is memory allocated when declaring an array in C plus plus?

It depends how the array is declared (fixed size or variable size) and where it is declared (global scope or local scope).

If the array is declared in global scope (outside a function) and is fixed size, it will be allocated in static memory. If it is variable size, the pointer is stored in static memory while the array itself is allocated on the heap. The pointer in static memory points to the start address of the array in heap memory.

If the array is declared in local scope (inside a function) and is fixed size, it will be allocated on the stack in whichever thread the function was called. If it is variable size, the local pointer is stored on the stack while the array is allocated on the heap. The pointer will fall from scope when the function returns so the array must not be allowed to outlive the function in which the pointer is declared. If the array must outlive the function that allocates the array, the pointer must be declared at a higher scope in the call stack and must be passed by reference to or returned by value from the function that allocates the array.

If you provide your own memory manager, however, an array may be allocated wherever the memory manager's memory pool is allocated, be it in static memory, the stack or the heap. A memory manager essentially allocates an array of bytes which you can then utilise as you see fit (the array of bytes will be allocated as per the previous description for arrays in general).

Importance of virtual functions?

Private virtual functions are useful when you expect a particular method to be overridden, but do not wish the override to be called from outside of the base class. That is, the base class implementation and its overrides remain private to the base class.


Private virtual methods are particularly useful in implementing template method patterns, where certain algorithmic steps need to be deferred to subclasses, but where those steps need not be exposed to those subclasses. In many cases the private virtual methods will be declared pure-virtual, thus rendering the base class an abstract base class.


What is a constructor initialization list?

The constructor initialisation list is the most efficient method of initialising class members, including primitive members. You use it always and without exception to ensure efficient construction.

Consider the following:

class foo

{

int m_data;

public:

foo(int data=0){ m_data=data; }

foo(const foo& f){ m_data=f.m_data; }

};

This class employs inefficient construction technique by initialising the member variables in the constructor bodies rather than the initialisation list. In other words, m_data is instantiated and initialised in two stages instead of one. It is not unlike the following two stage initialisation:

int m_data;

m_data =0;

A more efficient way of writing these lines is to initialise at the point of instantiation using a compound statement:

int m_data=0;

The same applies to class construction. By using the initialisation list, member variables are initialised at the point of instantiation, as per the following:

class foo

{

int m_data;

public:

foo(int data=0):m_data(data) {}

foo(const foo& f):m_data(f.m_data) {}

};

You will note that primitive members use object-oriented syntax in the initialisation list. This is not merely sugar-coating -- it applies to all members, including base classes. This makes it possible to invoke specific base class constructors, rather than the default constructor that would be implicitly invoked (or the base class copy constructor in the case of a derived class copy constructor).

Consider the following:

class base

{

int m_data;

public:

base(int data=0):m_data(data) {}

base(const base& b):m_data(b.m_data) {}

};

class derived : public base

{

public:

derived(int data=0):base(data) {}

derived(const derived& d):base(d) {}

};

Note how the derived class default constructor invokes the base class default constructor, but passes the data argument to it. Had you not used the initialisation list you'd have to construct base, then derived, and then initialise the base class member via a setter. Clearly the initialisation list is more efficient because the base class can be initialised before derived is even instantiated, which cannot happen until the base class is fully-instantiated.

Note also that the copy constructor specifically invokes the base class copy constructor. Although the argument, d, is not a base class, it is a type of base class, thus there is no need to upcast the argument.

Ultimately, it can be seen that the constructor bodies are largely redundant. You still need a constructor body, even an empty one, but most of the time you will use the body for debug trace code. There will be times, however, where the class initialisation list cannot fully initialise a member because one or more arguments require more complex processing (such as calling a complex setter). In this case, you must use the constructor body. However, you must still perform as much initialisation as is possible via the initialisation list to ensure the most efficient construction method. Only those members that require additional processing need not be initialised, but it costs nothing to initialise them to an arbitrary or default value.

The initialisation list is vital in the case of the copy constructor, as passing an object to a function by value will automatically invoke the copy constructor. If any member variables are embedded objects, or the object is derived from one or more base classes, then their copy constructors will be invoked as well. Therefore it pays to make construction as efficient as possible when copying objects. However, the same applies to any constructor. The more efficient the constructor performs, the better your programs will perform, especially in complex hierarchies where objects may be deeply embedded within other objects that are themselves embedded.

What is the difference between C and java?

You're comparing apples and oranges. C is a procedural language. You can, using structures and functions to access those structures do everything you can in Java. In fact, if you look into GObject, the object oriented method of programming in GTK (the Linux toolkit) people do this all the time. In fact they have pretty much implemented C++ manually using a programming style and macros.

C++ and Java have a great deal more in common. From a language perspective, they are nearly identical. Java is arguably cleaner as it doesn't depend on forward declaration and therefore all functions are coded directly within the class definitions themselves. C++ is arguably more powerful as you have direct access to the hardware of the system and it's also possible to write code in such a way that it is guaranteed to be compiled an optimized in a specific manor.

For application development, Java is often faster (performance and in the time it takes to get the job done). For system level development, C++ is almost always a clear winner. I won't detail it as it's far beyond the scope of the question.

There are two key differences between Java and C++ to a programmer.

1) Java is a garbage collected language

This means you can allocate memory and just forget about it when you're done. Some people say this leads to ugly code and quite frankly, I agree. Bad programmers can be REALLY bad programmers in Java and get away with it. C++ a C++ program will tend to crash your machine if you write it badly. The selling point of garbage collection is performance. It allows the runtime system of the language to clean up when there's time to do it instead of having to clean up during time critical moments. In C++ this type of behavior has to be coded manually and requires a great deal of strategic planning to accomplish.

2) Java has a "good" defined set of standard class libraries.

C++ has libraries also, but only a small percentage of programmers use them because many of us (me included) consider them to be a plague on the language. They're VERY over-engineered and can be very hard to debug. Java's libraries are a lot cleaner even if they have serious inconsistencies (this may spur a political debate, but I offer my opinion and the arguments I've heard from others).

Neither language is particularly good. Neither runtime is particularly modern. There are newer technologies such as C#/.NET and others which have arguably learn from C++ and Java and built upon what was learned.

If you're learning to program, I recommend using C++ with Qt (from Nokia) as it gives you almost the best of both worlds. If you're using one and looking to switch to the other. It should be a smooth transition, the languages are basically the same.

If you're asking about internal data structure. The two languages aren't comparable as Java doesn't have a strict internal structure definition and therefore can't be compared.

P.S. - For a bonus, Java's best feature is relocatable memory. Because it forces you to never use memory locations directly (pointers), so the java virtual machine can relocate your memory in order to make room for larger allocations that otherwise wouldn't fit without paging or asking the OS for more RAM. This can make your applications more efficient as virtual memory paging is far more expensive than simply defragging the memory occasionally.

What happens if recursion function is declared inline?

An inline function replaces the call to the function by the body of the function, thus reducing the overhead of saving the context in stack. This is good for functions which are small in size and called occasionally. A recursive function calls an instance of itself and thus can be a deeply nested. Different compilers handle this differently. Some will inline it up to a certain depth and then call a non-inlined instance for further recursion; others will not inline the function at all and generate a normal function call.

How do you get free borland c plus plus software?

There are many vendors of C++ compilers. Your choice depends on what platform you use, and whether or not you want paid support. Two compilers (remember, there are many) are GCC, at gcc.gnu.org, and Visual Studio, at www.microsoft.com/vstudio. Be sure to review the requirements, cost, and license details before you choose.

How implemention of election algorithm in c plus plus language?

#include<stdio.h>

#include<conio.h>

#include<process.h>

struct proc

{

int live;

int identifier;

}process[10];

int n,cordinator=1;

/******************* DISPLAY PROCESSES **********************/

void display()

{

int i;

printf("\n PROCESSES ARE\n\n");

printf("Processes ");

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

{

printf("P%d\t",i);

}

printf("\nlive ");

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

{

printf("%d\t",process[i].live);

}

printf("\nidentifier ");

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

{

printf("%d\t",process[i].identifier);

}

}

/************ BULLY ALGORITHM ****************************/

void bully()

{

int ch,c,id,i=0,cordinator,init,max=-99;

cordinator=i;

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

{

if(process[cordinator].identifier<process[i].identifier&& process[i].live==1)

cordinator=i;

}

printf("\n\n CURRENT CO-ORDINATOR IS=P%d",cordinator);

while(ch!=4)

{

printf("\n\n\n *** BULLY ALGORITHM ***");

printf("\n1.Crash a Process\n2.Activate Process\n3.Display\n4.Exit");

printf("\nENTER UR CHOICE");

scanf("%d",&ch);

switch(ch)

{

case 1:printf("\n Enter the process id to crash");

scanf("%d",&id);

if(process[id].live==0)

{

printf("\n Already crashed process");

}

else

{

process[id].live=0;

printf("\n process P%d is crashed",id);

if(id==cordinator)

{ while(1)

{

printf("\n Enter process id who intiates election");

scanf("%d",&init);

if(process[init].live==0)

{

printf("\n the selected process is crashed");

}

else

{

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

{

if(i!=init&& process[i].identifier>process[init].identifier)

printf("\n Election MSG sent from %d to %d",init,i);

}

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

{

if(i!=init)

{

if(process[i].identifier>process[init].identifier&&process[i].live!=0)

{

printf("\n OK from %d to %d",i,init);

}

}

}

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

{

if(max<process[i].identifier && process[i].live!=0)

{

cordinator=i;

max=process[i].identifier;

}

}

printf("\n\n NEW CO-ORDINATOR IS=P%d",cordinator);

break;

}

}

}

}

break;

case 2:printf("\n Enter process id to activate");

scanf("%d",&id);

if(process[id].live==1)

{

printf("\n Process %d is already active",id);

}

else

{

process[id].live=1;

printf("\n Process %d activated",id);

}

if(process[id].identifier>process[cordinator].identifier)

{cordinator=id;

printf("\n NEW CO-ORDINATOR IS=P%d\n\n",id);

}

break;

case 3:display();

break;

case 4:break;

}

}

}

/************ RING ALGORITHM ****************************/

void ring()

{

int ch,c,id,i=0,init,max=-99,last;

// cordinator=i;

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

{

if(process[cordinator].identifier<process[i].identifier&&process[i].live==1)

cordinator=i;

}

printf("\n\n CURRENT CO-ORDINATOR IS=P%d",cordinator);

while(ch!=4)

{

printf("\n\n\n *** RING ALGORITHM ***");

printf("\n1.Crash a Process\n2.Activate Process\n3.Display\n4.Exit");

printf("\nENTER UR CHOICE");

scanf("%d",&ch);

switch(ch)

{

case 1:printf("\n Enter the process id to crash");

scanf("%d",&id);

if(process[id].live==0)

{

printf("\n Already crashed process");

}

else

{

process[id].live=0;

printf("\n process P%d is crashed",id);

if(id==cordinator)

{ while(1)

{

printf("\n Enter process id who intiates election");

scanf("%d",&init);

if(process[init].live==0)

{

printf("\n the selected process is crashed");

}

else

{ last=init;

printf("\nElection MSG sent from =%d",last);

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

{

if(i!=init)

printf(" ->%d",i);

}

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

{

if(i!=init)

printf("->%d",i);

last=i;

}

/*

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

{

if(i!=init)

{

if(process[i].identifier>process[init].identifier&&process[i].live!=0)

{

printf("\n OK from %d to %d",i,init);

}

}

} */

// max=process[init].identifier;

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

{

if(max<process[i].identifier && process[i].live==1)

{

cordinator=i;

max=process[i].identifier;

}

}

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

{

if(max<process[i].identifier && process[i].live==1)

{

cordinator=i;

max=process[i].identifier;

}

}

printf("\n\n NEW CO-ORDINATOR IS=P%d",cordinator);

break;

}

}

}

}

break;

case 2:printf("\n Enter process id to activate");

scanf("%d",&id);

if(process[id].live==1)

{

printf("\n Process %d is already active",id);

}

else

{

process[id].live=1;

printf("\n Process %d activated",id);

if(process[id].identifier>process[cordinator].identifier)

{

printf("\n NEW CO-ORDINATOR IS=P%d\n\n",id);

cordinator=id;

}

}

break;

case 3:display();

break;

case 4:break;

}

}

}

void main()

{

int ch,i,c;

clrscr();

printf("\n ENTER NO. OF PROCESSES");

scanf("%d",&n);

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

{

printf("\nEnter P%d process live or not(0/1)",i);

scanf("%d",&process[i].live);

printf("\nEnter P%d process identifier",i);

scanf("%d",&process[i].identifier);

}

display();

while(1)

{

printf("\n\n\n**** ELECTION ALGORITHM ****");

printf("\n1.BULLY ALGORITHM\n2.RING ALGORITHM\n3.EXIT");

printf("\n\n ENTER UR CHOICE");

scanf("%d",&ch);

switch(ch)

{

case 1:bully();

break;

case 2: ring();

break;

case 3:exit(0);

}

}

}

What are callback functions?

In computer science, a callback is executable code that is passed as an argument to other code. It allows a low level software layer to call a function occurring in a higher level layer. Usually the higher level code first calls a function within the lower level code passing to it a pointer or handle to another function. Then the lower level function in the course of executing may call the passed-in function any number of times to perform some subtask. Another option is that the lower level function registers the passed-in function as a handler that is to be called asynchronously by the lower level at a later time in reaction to something. A callback can be used as a simpler alternative to polymorphism and generic programming, in that the exact behavior of a function can be dynamically determined by passing different (yet compatible) function pointers or handles to the lower level function. This can be a very powerful technique for code reuse.