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

Write a c program to print fibonacci series using do while loop?

#include<iostream>

using namespace std;

#define MIN 1

#define MAX 1000000

int main()

{

int num;

char c;

do

{

cout << "Enter a number from " << MIN << "-" << MAX << " (0 to quit): ";

cin >> num;

while(cin.fail() num < 0 num > MAX)

{

if( cin.fail() )

{

cin.clear();

cin >> c;

}

cout << "Invalid number, try again: ";

cin >> num;

}

if(num)

{

cout << "\nFibbonacci series for n, where 1 <= n <= " << num << ":\n\n";

int n = 1, x = 0, y = 0;

do

{

cout << n;

x = y;

y = n;

n = x + y;

if( n < num )

cout << ", ";

}while( n < num );

cout << endl << endl;

}

}while( num );

return( 0 );

}

Why is a destructor function required in C plus plus classes?

A destructor is not a function per-se. Functions have returns values but destructors do not (not even void). However, other than the lack of a return value, a destructor's body is no different to a function body.

Contrary to belief, destructors are not required by every class of object. Destructors are only required when we need to explicitly release a resource when an object of the class falls from scope, but not all resources need to be released explicitly. Consider the following class:

struct point {

int x, y;

};

This class does not require a destructor because it is self-contained. That is, all the resources consumed by an object of the class are contained within the object itself, thus when the object falls from scope, the memory it consumed is automatically released. There is nothing to destroy.

Now consider the following class:

class my_vector {

std::vector<int> v;

};

Again, this class requires no destructor. When objects of this class fall from scope, the vector's destructor is invoked, releasing its resources. Thus the only resource consumed by this class is the vector itself, and that's self-contained by the class.

Now let's consider a class that does require a destructor:

template<typename T>

class smart_pointer {

T* ptr;

// ...

};

Here, we have a class that encapsulates a "naked" pointer variable of some type T. That pointer could feasibly refer to any object of type T in memory. However, being a "smart pointer", the assumption is that objects of this class will "own" the memory they refer to. As the owner, it makes sense to yield ownership whenever object's of the class fall from scope. If we didn't provide a destructor, ptr would fall from scope, but the memory it referred to would not. So to ensure the memory is released, we must explicitly release it via the class destructor:

template<typename T> class smart_pointer {

T* ptr;

// ...

public:

~smart_pointer () { delete ptr; }

};

To summarise: a destructor is only required when an object acquires a non-shared resource that is not released automatically when objects of the class fall from scope. A vector is a resource handle, so when it falls from scope, its resources are released automatically. Similarly with smart pointers. However a "naked" pointer is not a resource handle, so if our class "owns" a resource by holding a pointer to it, then we must release that pointer when objects of the class are destroyed. Resources cover many things besides raw memory. If we hold a reference to an open file, it would be prudent to close the file before the reference falls from scope. With a resource handle we get that assurance. Thus if we use resource handles rather than "raw" resources, then we need never write any destructors.

There can be other reasons to require a destructor besides resource management, such as to write an entry in a log file upon destruction, however resource management and other "housekeeping" task are not a requirement of every class thus a destructor is not required by every class.

Why objects are not used to acces the static class members?

Static members are members of the class, not an instance of the class.

All instances of a class have access to all their static members. Derived classes have access to both protected and public statics, while public statics are fully accessible.

Think of static members as being global variables or functions, but scoped to the class rather than being globally accessible (and therefore publicly accessible).

Consider the following example. A private static member variable, count, is declared. Note that it must be initialised immediately after the class declaration, but outside of a code block. Were it declared public it could be initialised in a code block, but the class needs to maintain control over it, thus it is completely hidden from all outside influence.

The two constructors increment count while the destructor decrements count. Thus count maintains a running total of all the instances of the class (much like a reference counter). Note that all instances of the class have direct access to the static member. Note also that if other parametrised constructors are declared, each must increment countindependently.

The public static accessor method, GetCount(), returns the current value of count (returning by value, not by reference). There is no equivalent set mutator, thus countis a read-only variable -- it cannot be altered from outside of the class.

#include

class MyClass{

public:

MyClass(){ ++count; }

MyClass(const MyClass & copy){ ++count; }

~MyClass(){ --count; }

public:

static unsigned int GetCount(){ return( count ); }

private:

static unsigned int count;

};

// Initialise the static member:

unsigned int MyClass::count = 0;

void PrintCount()

{

printf( "There %s currently %u instance%s of MyClass.\n",

MyClass::GetCount() 1 ? "" : "s" );

}

int main()

{

MyClass * myClass[10];

// At this point there are no instances.

PrintCount();

printf( "\nCreating instances of MyClass...\n" );

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

{

myClass[i] = new MyClass();

PrintCount();

}

printf( "\nDestroying instances of MyClass...\n" );

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

{

delete( myClass[i] );

PrintCount();

}

return( 0 );

}

How do you compile and run C programs on the Macintosh?

The first step is to install the XCode developer tools that comes with OSX. You can do this by looking on your OSX install disc. There should be a folder for optional installs, and a package for XCode. This will automatically install gcc, a C compiler, on your machine. Next, find the Console in the Utilities folder. It opens a UNIX shell. Move to the directory that your c file is in (you can find more information about UNIX elsewhere if you need to). Let's say your C file is named myfile.c. To compile it, type: gcc myfile.c This will compile your program, and name the compiled program a.out. To run it, type: ./a.out I hope that helps. Brina

Who invented c plus plus and when?

C++ was originally called 'C With Classes' in 1978, and was renamed by its developer, Bjarne Stroustrup, in 1983. The new name literally meant 'the successor to C', although it should really have been called ++C (prefix increment) rather than C++ (postfix increment), since the former returns C+1 (the successor to C), while the latter returns C.

Write a c plus plus program of array to pointers?

#include
void

printarr(int

a[]);
void

printdetail(int

a[]);
main()
{
int

a[5];
for

(int

i = 0;i<5;i++)
{
a[i]=i;
}
printdetail(a);
}
void

printarr(int

a[])
{
for

(int

i = 0;i<5;i++)
{
printf("value in array %d\n"

,a[i]);
}
}
void

printdetail(int

a[])
{
for

(int

i = 0;i<5;i++)
{
printf("value in array %d and address is %8u\n"

,a[i],&a[i]);
}
}
void

print_usingptr(int

a[])
{
int

*b;

Explain term composition with example in c plus plus?

Composition relates to the way in which complex objects can be constructed from smaller, simpler objects. We refer to this as object composition. While simple objects typically contain one or more embedded primitive member attributes, such as int, char, float and so on, composite objects typically embed other objects (often in addition to other primitive attributes), and each of those objects may themselves be composite or they may be simple. This allows highly complex object models to be constructed such that each object within a composition is self-contained and ultimately operates no differently to how it would operate if it were a standalone object. The composite object effectively acts as an object coordinator, calling specific methods upon the simpler objects as required. In other words, the actual workload is delegated to the object or objects that are actually responsible for that workload, and they themselves may delegate to simpler objects, and they to theirs. The composite object's only real workload is in processing any relevant results of those delegations. In other words, a simple function call through a member method of the composite object can produce a cascade of member methods within the embedded objects, each of which works completely independently, but the results of which can be combined by the containing object in order to produce highly complex behaviour.

By way of an example, a motor car is built up from thousands of individual but ultimately simple components, such as nuts and bolts, switches, cogs, levers, wheels and so on. Some of those simple objects are combined to produce more complex objects, such as an engine, a transmission unit, a steering mechanism, door locks, and so, on. Ultimately, they all combine to produce a car. But no matter how complex a composite object is, the behaviour of their embedded objects does not change: a nut and bolt is still a nut and bolt whether it is holding a door hinge onto a chassis, or a suspension strut to a wheel hub. In other words, the job of physically holding one component to another is delegated to the nut and bolt, but is coordinated according to the object that embeds the nut and bolt, while that object is coordinated and delegated to by the object that contains it, and so on.

Selection Sort Program in c and c plus plus?

The following code demonstrates the implementations for bubble sort, insertion sort and selection sort, in C++.

#include<iostream>

#include<time.h>

#include<iomanip>

#include<string>

void swap(int& x, int& y)

{

x^=y^=x^=y;

}

void bubble_sort(int* A, int size)

{

while(size)

{

int n=0;

for(int i=1; i<size; ++i)

{

if(A[i-1]>A[i])

{

swap(A[i-1], A[i]);

n=i;

}

}

size=n;

}

}

void insertion_sort(int* A, int size)

{

for(int i=1; i<size; ++i)

{

int value=A[i];

int hole=i;

while( hole && value<A[hole-1] )

{

A[hole]=A[hole-1];

--hole;

}

A[hole]=value;

}

}

void selection_sort(int* A, int size)

{

for(int i=0; i<size-1; ++i)

{

int j=i;

for(int k=i+1; k<size; ++k)

if(A[k]<A[j])

j=k;

if( i!=j )

swap(A[i],A[j]);

}

}

void sort(int* A, int size, int sort_type)

{

switch(sort_type)

{

case(0): bubble_sort( A, size );

case(1): insertion_sort( A, size );

case(2): selection_sort( A, size );

}

}

int* copy_array(int* A, int size)

{

int* copy=new int[size];

memcpy(copy, A, size*sizeof(int));

return(copy);

}

void print_array(int* A, int size, char* prompt)

{

std::cout<<prompt<<"\t";

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

std::cout<<std::setw(2)<<A[i]<<" ";

std::cout<<std::endl;

}

int get_rand(int range_min=0, int range_max=RAND_MAX)

{

return((int) ((double)rand() / (RAND_MAX + 1) * ((range_max + 1) - range_min) + range_min));

}

int input_char(std::string prompt, std::string input)

{

char ch;

do

{

std::cout<<prompt<<": ";

std::cin>>ch;

}

while(input.find(ch)==std::string::npos);

return(input.find(ch)%(input.size()/2));

}

int main()

{

srand((unsigned) time(NULL));

int size = get_rand( 10, 80);

if( int* A = new int[size] )

{

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

A[i]=get_rand( 1, size );

int choice=input_char("Please select a sorting method:\n[B]ubble, [I]nsert, [S]election", "bisBIS");

std::cout<<"You chose ";

switch(choice)

{

case(0): std::cout<<"bubble"; break;

case(1): std::cout<<"insertion"; break;

case(2): std::cout<<"selection"; break;

}

std::cout<<" sort...\n"<<std::endl;

print_array( A, size, "Before sorting" );

sort(A, size, choice);

print_array( A, size, "After sorting" );

delete [] A;

}

return(0);

}

Why does C plus plus allows static binding and not dynamic binding?

Dynamic binding, or late binding, is when the object code for the class does not get loaded into memory until it is needed. This saves time at module load time, at the cost of delayed execution for the first invocation.

In c plus plus Who tells the compiler that a specific class will be declared later in the program?

A forward declaration. However forward declarations can only be used when the class is used as a pointer or reference prior to its definition, otherwise it must be defined before it is used.

class A; // forward declaration

class B {

A& data; // reference to class that has yet to be defined

};

class A {}; // definition

Importance of data structure?

Data structure is important since it dictates the types of operations we can perform on the data and how efficiently they can be carried out. It also dictates how dynamic we can be in dealing with our data; for example it dictates if we can add additional data on the fly or if we need to know about all of the data up front. We determine which data structures to use to store our data only after we've carefully analyzed the problem and know at least what it is we hope to do with the data; for example if we'll require random access, or sequential access, or the ability to move both forward and backward through the data.

What is the if-else statement in c plus plus programming language?

The if-then-else inline command is shown below:

returnvalue = (condition) ? (truePart) : (falsePart);

-----------

According to the C standard, this command does exist in the C coding language in the same way as it exists in C++ and comparable languages.

http://users.ece.cmu.edu/~eno/coding/CCodingStandard.html

What is the difference between function prototyping and function overloading?

Function prototypes determine the return type, the name of the function, the argument types expected by the function, and the arity of the function. Function prototyping is used to separate interface from implementation. In C++ all functions must be declared before they are called, thus we use prototypes to provide forward declarations for those functions that have yet to be defined/implemented. We can also use forward declarations for incomplete types such as template functions and classes, however the definition/implementation must be visible to compiler before the function or class is used. In these cases the definitions are typically placed in the same header as the declarations.

It is important to note that a definition is also a declaration, and therefore both are also prototypes. The only real difference is that prototypes do not require names for the formal arguments. Even if you provide argument names in your prototypes, they will be ignored by the compiler. The argument names within the definition are the only names of any relevance.

Function overloading is where two or more functions share the same name within the same namespace, but have different signatures. The signature of a function is essentially the same as its prototype but excludes the return type, thus overloads cannot differ by return type alone. The compiler uses the function signature to differentiate between your overloads.

All function signatures within a namespace must be unambiguous, thus you cannot have two functions with the same name and arguments that are co-variant. For example, the following overloads are invalid because a size_t type is co-variant with unsigned int type, thus the compiler cannot differentiate them.

unsigned int max(unsigned int, unsigned int);

size_t max(size_t, size_t);

What is the meanig of return 0 in c plus plus?

The return statement "returns" control to the function that invoked the function executing the return statement. Adding a value, such as return 0, adds a "return value", which the invoking function can inspect. The type of the returned value is declared along with the function's declaration, such as int myfunction(...) - it can be any type, not just an int.

If the "invoking function" is the operating system, the return statement returns control back to the operating system. The value of the return, in this case an int, tells the operating system what the result of the execution of the entire program was.

By convention, but this is operating system, shell, and/or programmer determined, a return value of 0 normally means "success", while anything else means "some kind of error", and the actual value identifies what kind of error.

Write a program in c plus plus to create an analog and digital clock using computer graphics?

#include "stdio.h"

#include "conio.h"

#include "dos.h"

void main()

{

int h,m,s;

h=0;

m=0;

s=0;

while(1)

{

if(s>59)

{

m=m+1;

s=0;

}

if(m>59)

{

h=h+1;

m=0;

}

if(h>11)

{

h=0;

m=0;

s=0;

}

delay(1000);

s=s+1;

clrscr();

printf("\n DIGITAL CLOCK");

printf("\n HOUR:MINUTE:SECOND");

printf("\n%d:%d:%d",h,m,s);

}

getch();

}

Definition of structure in c plus plus?

A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. A structure declaration forms a template that may be used to create structure objects (that is, instances of a structure). The variables that make up the structure are called members. (Structure members are also commonly referred to as elements or fields).

Can you overload static functions in c plus plus?

Yes, but overloads cannot differ by return type alone. The signatures must differ by the number and/or the type of the arguments.

What are the advantages of using a symbolic constant rather than a literal constant in c plus plus?

The main two I can think of:

  1. It gives more meaning to the constant. eg using PI instead of 3.14159 makes it easier to understand what's going on when calculating things like a = PI * r * r;
  2. Should the constant for the program need to be changed, only one occurrence needs to be changed (in a header file) instead of all usages.

Write a c plus plus program to sort the names in asecending order using array of objects?

#include<iostream>

#include<vector>

#include<string>

#include<algorithm>

int main()

{

std::vector<std::string> str_array = { "John", "Bill", "Alan", "Craig"};

std::sort (arr.begin(), arr.end());

}

Why do you need assembly language?

Assembly language is more human-readable than machine language. Generally, statements in assembly language are written using short codes for the instruction and arguments, such as "MOV $12 SP", as opposed to machine language, where everything is written as numbers. Assembly language can have comments and macros as well, to ease programming and understanding.

Generally, programs called "assemblers" transform assembly language to machine language. This is a relatively straightforward process, there being a clear 1-to-1 transformation between assembly and machine language. This is as opposed to compilers, which do a complicated transformation between high-level language and assembly.

--------------------------------------------------------------------

ASSEMBLY is the key word to define the difference between Machine Language and Assembly. . Assembly language assembles steps of MACHINE CODE into SUB-ROUTINES defined by simple text words:

Such as: the assembly command 'ADD' may represents 20-30 machine commands.

Can private members of a class be inherited?

All fields and methods of a class are inherited:

public class A

{private int x =10;public int XVal{get{return x;}}}

public class B:A

{public B(){x = 20;}}

What are the advantages of using a recursive function in c?

Advantages:
Through Recursion one can Solve problems in easy way while
its iterative solution is very big and complex.
Ex : tower of Hanoi
You reduce size of the code when you use recursive call.

Disadvantages :
Recursive solution is always logical and it is very
difficult to trace.(debug and understand)

Before each recursive calls current values of the varibles
in the function is stored in the PCB, ie process control
block and this PCB is pushed in the OS Stack.
So sometimes alot of free memory is require for recursive
solutions.

Remember : whatever could be done through recursion could be
done through iterative way but reverse is not true.

How do you write a c plus plus program to print aaaa aaab aabb abbb bbbb?

#include<iostream>

#include<string>

#include<algorithm>

bool compare_no_case (const char a, const char b)

{

return tolower(a) < towlower (b);

}

int main()

{

std::string s {"This is the string to be sorted!"};

std::cout << "Unsorted:\t"" << s << ""\n";

std::sort (s.begin(), s.end(), compare_no_case);

std::cout << "Sorted\t:"" << s << ""\n";

}

Explain how a private data of a base class can be accessed by publicly derived class?

The only way that private attributes of a base class can be accessed by a derived class (protected or public) is through a protected or public method in the base class.

The protected or public method is the interface through which access to the attributes is defined and controlled.

What is sub classing in c plus plus?

Class in C++ is just the same meaning as in any other OO(object-oriented) languages. In the world of OO, anything are classes, which have properties, function to work. In other words, class is a method to organize things to work together.