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 the importnce of file handling?

Most applications cannot operate efficiently (or sometimes even at all) without some method to save and load data of some sort. While a database may suffice in many cases, in others it's impractical (either because availability of a DBMS isn't guaranteed, the data stored isn't enough to justify the added overhead, etc.) In such cases, using a file of some sort is often the only other reasonable option. Doing so requires file handling commands to open and close the file, read from and write to the file, etc.

What supports reusability and extensibility of classes in c plus plus?

There are two ways to reuse a class in C++. Composition and inheritance. With composition, any class data member can be an instance of an existing class. With inheritance, we can derive a new class from an existing class. Either way, we create a new class of object with all the properties of the existing class which can be extended and/or replaced with properties of our own.

How do you handle object array?

Exactly as you would any other type of array. An object's size is determined in the same way a structure's size is determined, by the sum total size of its member variables, plus any padding incurred by alignment.

However, you cannot create arrays of base classes. Arrays of objects can only be created when the class of object is final; a class that has a private default constructor, otherwise known as a "leaf" class. This is because derived classes can vary in size; array elements must all be the same size.

To create an array of base classes you must create an array of pointers to those base classes instead. Pointers are always the same size (4 bytes on a 32-bit system).

Static arrays are ideally suited to arrays of leaf objects where the number of objects never changes, or the maximum number of objects is finite and fixed. Although you can use dynamic arrays of leaf objects, you will incur a performance penalty every time the array needs to be resized, because every object's copy constructor must be called during the reallocation. Dynamic arrays are better suited to arrays of pointers to objects -- only the pointers need to be copied during resizing, not the objects they point to.

How is dynamic initialisation achieved in c plus plus?

The C++ standard has this to say about dynamic initialisation:

"Objects with static storage duration shall be zero-initialised before any other initialisation takes place. Zero-initialisation and initialisation with a constant expression are collectively called static initialisation; all other initialisation is dynamic initialisation."

How do you make chess game in c plus plus programming?

This question cannot be answered here. Go to amazon.com and find a book about chess-programming.

Who created c and c plus plus and java?

Dennis Ritche developed C for bell labs for the unix operating system http://en.wikipedia.org/wiki/C_(programming_language) Bjarne Stroustrup developed C++ http://en.wikipedia.org/wiki/C%2B%2B

How do you increment date using strdate in c plus plus?

In short, you don't.

The strdate() function returns a formatted string that represents the current date. It is not intended that this result be used in a date calculation such as increment. The complexities of converting back to month day and year, and then dealing with the special rules of the Gregorian calender, along with leap years is unrealistic, given that there are library functions that will do this for you already. Try this...

#include <time.h>

#include <iostream>

using namespace std;

...

char cdate[9];

time_t tt = time(NULL) + 86400; // tomorrow

struct tm *tomorrow;

tomorrow = localtime (&tt);

strftime(cdate, 9, "%m/%d/%y", tomorrow);

cout << cdate << endl;

What is the difference between abstract class and normal class?

Any class which has one or more abstract methods is called an abstract class. But in the normal class we can't have any abstract methods.

We cannot create an object for the abstract classes.

When we inherit the abstract class we should implement the abstract method which we inherit.

How do C and C plus plus differ in terms of data abstraction and classes and structs?

They differ insofar as C does not use object-oriented programming at all -- there are no classes (only structures), therefore there was nothing to abstract. C++ (which literally means 'the successor to C') is an extension of C that primarily adds object-orientated support to the language. Everything you can do in C you can also do in C++, but with the added benefits of OOP you can do a whole lot more, more easily, including the creation of abstract data types.

Why enumerator data type is used in c plus plus?

Enumerated data types are a set of user-defined constants called enumerators that provide context to a range of values. For instance, if you define the following constants:

static const int Monday=0;

static const int Tuesday=1;

// ...

static const int Sunday = 6;

static const int January=0;

static const int February=1;

// ...

static const int December=12;

Then there's nothing to prevent you from coding the following:

int var1 = January;

int var2 = Tuesday;

// ...

int var3 = var1 + var2;

What exactly does var3 represent? A month? A day? Or something else entirely? The problem is the compiler can't help you because you've not actually done anything wrong. As far as the compiler is concerned, all you've done is add two ints together to produce a third int. Whether it makes sense or not is another matter altogether.

Enumerations exist to prevent this sort of problem.

enum day { Monday, Tuesday, ..., Sunday };

enum month { January, February, ..., December };

month var1 = January;

day var2 = Tuesday;

// ...

int var3 = var1 + var2;

Now the compiler will tell you there is no suitable plus operator that accepts an l-value of month and an r-value of day.

Enumerators have an implied type of signed int, but you can also specify an alternative type, provided it is an intrinsically primitive integral type, such as int, char, or short, whether signed or unsigned. However, even when typed, you cannot use any operators upon them unless you specifically provide an operator overload to cater for them. Thus the following will not work:

for( day d=Monday; d<=Sunday; ++d )

// ...

Without a suitable operator overload for the prefix increment operator, you must use an explicit cast, such as follows:

for( int i=Monday; i<=Sunday; ++i )

{

day d = reinterpret_cast<day>(i);

// ...

}

Although you've got to work a bit harder to use enumerators, the point is that the additional work is required in order to prevent problems such as those highlighted at the start of this answer. Enumerators enlist the compiler to help you spot errors, forcing you to make a conscious decision whenever you want to override the compiler's help, but ultimately ensuring your code is as robust as possible.

What is a sparse matrix in c programming?

Sparse matirx can be represented 1-dimensionally, by creating a array of structures, that have members sumc as: Struct RM{int ROW,int COL, int non_zero}; struct RM SM[Number_non_Zeros +1]; then input row,col for each non-zero element of the sparse matrix. if still unclear please fell free to requestion or query on ikit.bbsr@gmail.com, specifying clearly the question in the subject. Chinmaya N. Padhy (IKIT)

What are the limitations of friend function?

Only that they cannot be inherited by derived classes. This is "a good thing". Other than that, a friend function has full access to a class' private and protected members and you cannot limit its scope.

Friendship in C plus plus?

Friends are used to extend the interface of a class. They are useful in that certain classes and functions may require private access to other class members, particularly where two classes are closely coupled (such as parent and child classes).

Friends should never be used when suitable interfaces already exist. If you have to expose an interface simply to allow an external function or class to do its job, then it would be better to declare the function or class a friend rather than expose an otherwise unnecessary interface. The key to good encapsulation is to minimise your interface as much as possible -- only expose what you absolutely must expose.

Before allowing friendship, always consider whether the function or class can be declared a member of the class itself. Static member functions are often a good choice here. However, certain functions, such as stream insertion and extraction overloads, cannot be implemented as member functions and must be implemented as external functions. These are often cited as good examples of friend functions, however keep in mind that when suitable interfaces exist, friendship is unnecessary.

Although friends are not members of the class that declares them to be a friend, they must be treated just as if they were members. That is, you must have full control over the implementation in order to maintain encapsulation. But keep in mind that the purpose of a friend is purely to gain private access for which no public interface exists and where providing such an interface would do more to undermine your encapsulation than a friend would.

When should a member of a class be declared public?

When the member needs to be accessible from outside of the class. Private members are only accessible from within the class itself, including friends of the class. Protected members are the same as private members but are also accessible to derived classes. Derived classes therefore inherit both the protected and public members of its base classes.

Write a C program using dynamic memory allocation to subtract two matrices?

The easiest way would be to write a function that accepts two arrays and returns one.

Lets say you are working with two 2-dimensional arrays.

array<int,2>^ SubtractMatrices(int arr1[][2], int arr2[][2]);

void main()

{

int arr1[2][2] = {0,1,2,3};

int arr2[2][2] = {0,1,2,4};

array<int,2>^ newarr;

// array<int^,2>^ newarr[2][2] = SubtractMatrices(arr1, arr2);

}

array<int,2>^ SubtractMatrices(int arr1[][2], int arr2[][2])

{

array<int,2>^ newarr;

//Insert subtraction algorithm here

return newarr;

}

In this scenario you must pass the function 2 matrices, and then return a pointer to a new matrix.

Hmm, still seems to be an error in there with the return type. I'm not sure if that's the correct way to do it, I did this in Visual Studio's managed C++. .

What is the difference between a class method and object in object-oriented C?

Class methods are the member functions that act upon member variables. An object is an instance of a class. C does not support object-oriented programming, but C++ does.

Write a program in C plus plus that shows the following series 1 1 2 3 5 8 13 Using for Loop?

void main()

{

int a=0,b=1,c;

clrscr();

printf("%d",a);

printf("%d",b);

for(;c<=20;)

{

c=a+b;

a=b;b=c;

printf("%d",c);

}

getch();

}

What are the Application of tree and graph in data file structures?

Using binary tree, one can create expression trees. The leaves of the expression tree are operands such as constants, variable names and the other node contains the operator (binary operator). this particular tree seems to be binary because all the operators used are binary operators. it is also possible for a node to have one node also, in case when a unary minus operator is used.

we can evaluate an expression tree by applying the operator at the root to the values obtained by recursively evaluating the left and right sub trees.

What are the backslashes that are use in turbo C plus plus?

Backslashes are used to mark the start of an escape sequence which can be used within character arrays (strings) or as a single character. Thus the escpae sequence '\t' is the TAB character, '\n' is the newline character and '\r' is the carriage-return character. To print a literal backslash, you use a double backslash, '\\'. Note that the backslash and the escaped character that follow are treated as being one character (two bytes of UNICODE, or one byte of ASCII).

This convention is not unique to Turbo C. It was inherited from ISO C.

What type of logical access control method allows you to define who can access an object and type of access that they will have to that object?

That functionality is not available in generic C++, it is a function of the operating system and is therefore platform-specific. Even so, user-credentials cannot be used to determine who can access an object unless you employ some form of biometric security such as fingerprint identification, or a physical security system such as keycards. In the absence of these facilities, you would have to force the user to confirm their credentials every time the object was accessed. After all, the user who originally logged into the system is not necessarily the user currently using the system.

Why you use flag in programming?

We can use flag for many reasons depending upon ur logic but normally people use flag to check which control flow led to this o/p...hmmm to make it more clear EX : if(i%2==0) flag = 1 ; else flag = 0 ; ... ... ... if(flag) print "the number is even" Like this u can use to flag to de-bug ur code or to check the control flow

What does Microsoft Visual C plus plus Runtime Library mean?

The runtime library is a collection of routines that implements basic functionality of the platform. Routines such as I/O, memory control, startup, shutdown, common system functions, etc. are located in the runtime library.

What are the advantages of a class in C over a structure in C?

A C struct only has public member variables whereas a C++ class combines member variables with member functions; the methods that operate upon the data. Moreover, each member of a class can be assigned a different level of access from public, protected or private access, thus limiting the member's exposure. This allows classes to hide data and implementation details from outside of the class, exposing only as much as is necessary in order to use the class. Thus the class becomes entirely responsible for the integrity of its data, while its methods act as the gatekeepers to that data.


Note that in C++, a struct is exactly the same as a class, other than the fact that the members of a struct are public by default while members of a class are private by default, unless explicitly declared otherwise. Aside from that they operate in exactly the same way. In other words, a C++ struct is not the same as a C struct.



What is the code to convert digits in to words in C plus plus?

#include<iostream>

class expand

{

public:

expand(unsigned long long num):value(num){}

std::ostream& operator()(std::ostream& out)const;

private:

unsigned long long value;

static const char * const units[20];

static const char * const tens[10];

};

const char * const expand::units[20] = {"zero", "one", "two", "three","four","five","six","seven",

"eight","nine", "ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",

"eighteen","nineteen"};

const char * const expand::tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",

"eighty","ninety"};

std::ostream &operator<< (std::ostream &out, expand number)

{

return(number(out));

}

std::ostream &expand::operator()(std::ostream &out) const

{

const unsigned long long quintillion=1000000000000000000;

const unsigned long long quadrillion=1000000000000000;

const unsigned long long trillion=1000000000000;

const unsigned long long billion=1000000000;

const unsigned long long million=1000000;

const unsigned long long thousand=1000;

const unsigned long long hundred=100;

const unsigned long long twenty=20;

const unsigned long long ten=10;

unsigned long long multiple=quintillion;

unsigned long long remain;

if(value>=thousand)

{

while(multiple>value&&(multiple!=quintillionmultiple!=quadrillion

multiple!=trillionmultiple!=billionmultiple!=millionmultiple!=thousand))

multiple/=1000;

out<<expand(value/multiple);

switch(multiple)

{

case(quintillion):out<<"-quintillion"; break;

case(quadrillion):out<<"-quadrillion"; break;

case(trillion):out<<"-trillion"; break;

case(billion):out<<"-billion"; break;

case(million):out<<"-million";break;

case(thousand):out<<"-thousand";break;

}

if(remain=value%multiple)

{

if(remain<hundred)

out<<"-and";

out<<"-"<<expand(remain);

}

}

else if(value>=hundred)

{

out<<expand(value/hundred)<<"-hundred";

if(remain=value%hundred)

out<<"-and-"<<expand(remain);

}

else if(value>=twenty)

{

out<<tens[value/ten];

if(remain=value%ten)

out<<"-"<<expand(remain);

}

else

out<<units[value];

return(out);

}

int main()

{

for(unsigned long long ull=0; ull<0xffffffffffffffff; ++ull)

std::cout<<expand(ull)<<std::endl;

return(0);

}

How function declared in C plus plus?

Functions are declared by specifying the function return type (which includes any use of the const qualifier), the name of the function, and the function's argument types enclosed in parentheses (round brackets), which also includes any use of the const qualifier. The declaration ends with a semi-colon. Arguments may also be given default values but if any argument has a default value, all arguments that follow must also have default values.

[const] type name([[const] type [=value][, ...]]);

Declarations may also contain definitions in which case you must include the formal argument names that will be used by the definition. The definition (or implementation) must be enclosed in braces (curly brackets) and the semi-colon must be omitted.

[const] type name([[const] type arg1 [=value][, ...]])

{

statement;

}

Functions must be declared before they can be used. In most cases it is necessary to forward declare functions in a header. In these cases, default values must be omitted from the definition.

Functions that do not return a value must return void. Functions that do not accept arguments must still include the argument parentheses. Use of the void keyword to indicate no arguments is optional. Thus the following declarations are exactly the same (although declaring both in the same program would be invalid):

void f();

void f(void);

As well as the return type and argument types, class member functions (methods) can also be modified with the const qualifier:

struct obj

{

void f(void) const;

};

The const keyword assures the caller that the object's immutable members will not be modified by the function (that is, the internal state of the object's immutable data will remain unaltered). Also, when working with constant objects, only constant methods can be called.

Functions can also be declared static. In the case of external functions, the static keyword limits the visibility of the function to its translation unit. In the case of class methods, static member functions are local to the class as opposed to instances of the class. Static member functions do not have access to an implicit this pointer since they are not associated with any instance of the class but are accessible even when no instances of the class exist.