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

Can we use gotoxy function in C plus plus?

Ideally you would not manipulate std::cout using such a low-level function. Console output is intentionally generic so that output can be easily redirected to any output device that accepts a character stream. As such, this code will not work correctly if the user were to redirect output to a disk file or a printer, or use the output as input to another program. If you wish to format screen output in a non-generic manner, do not use the console, use a screen-specific context device instead.

#include<iostream>

#include<string>

#ifdef WIN32

#include<windows.h>

#endif WIN32

void gotoxy(int x, int y)

{

#ifdef WIN32

static HANDLE h = NULL;

if(!h)

h = GetStdHandle (STD_OUTPUT_HANDLE);

COORD c = { x, y };

SetConsoleCursorPosition (h,c);

#elif linux

printf("%c[%d;%df",0x1B,y,x);

#else

static_assert (false, "unsupported platform in gotoxy()");

#endif WIN32

}

void draw_box(unsigned x, unsigned y, unsigned width, unsigned height)

{

gotoxy (x, y);

std::cout << std::string (width, '*');

for (unsigned z=2; z<height; ++z)

{

gotoxy (x, ++y);

std::cout << "*";

gotoxy (x+width-1, y);

std::cout << "*";

}

gotoxy (x,++y);

std::cout << std::string (width, '*');

}

int main()

{

draw_box(10,10,5,4); // draw 5x4 box at {10,10}

gotoxy (0,25);

}

What are the merits and demerits of while loop and do while loop in c plus plus?

You use a while() loop when you want to test a condition before entering a loop for the first time, which may bypass the loop completely. The condition is also tested before beginning each iteration.

A do..while() loop always executes the loop at least once, and tests the condition at the end of each iteration before beginning a new iteration.

What is the difference between friend function and inheritance in c plus plus?

There is no such thing. When declaring a friend function only the explicitly-scoped friend is granted private access. The friend function may well be declared virtual within its own class but none of its overrides are granted access unless they are explicitly granted access.

How may the double variables temp weight and age be defined on one statement?

Use the comma operator:

double temp {1.0}, weight {5.5}, age {21.0};

Compare c plus plus and visual basic?

Visual Basic is a Windows-specific programming language, developed by Microsoft. C++ is a standard, generic and cross-platform programming language. Microsoft's implementation is called Visual C++, but it is not standards-compliant. Visual Basic requires a runtime library. C++ does not. Visual Basic is 100% object-oriented. C++ is not 100% object-oriented, but gives programmers greater freedom of choice. C++ is efficient, compact and performs extremely well on a wide variety of hardware. Visual Basic programs are inefficient, generally large, and much slower than equivalent C++ programs, and only run on Windows.

What does if statements in c plus plus implement?

C++ if() statements implements a comparison and a jump opcode. By way of example, consider the following code:

if( x 100 ) generates a compare and jump opcode (cmp and jne).

The cmp opcode compares the value of x with 64h (100 decimal) which will either set or clear ZF (the zero flag). If x is 100, then ZF will be unset, otherwise it will be set.

The jne (jump if not equal) opcode tests ZF. If it is set, then x was not 100 and the operand (1181934h) is passed to the PC register (the program counter). The IR (instruction register) will fetch the value from PC on the next cycle. This ultimately causes execution to jump to the statement immediately following the else clause of the if statement (the second printf statement).

If ZF is not set, then x really was 100 and the PC register remains unaffected. At that point the PC register will contain the value 0118191Bh, which is the next instruction after the if statement, thus execution simply falls through to the first printf statement. After processing the printfinstructions, execution will reach the else clause which simply forces a jump to bypass the second printfstatement.

Thus, one of the printf statements is executed and then execution continues from the instruction at 118194Bh, which is not shown but is the next instruction after the second printfstatement.

What is the purpose if declaring object with keyword const in c plus plus?

The const keyword transforms a variable into a constant. This means the constant cannot be altered via that constant's identifier. The const keyword can also be applied to a class instance method, such that the method will not alter a class instance's immutable members.

Note that the const keyword is merely a programming aid that provides assurances a constant will not be altered inadvertently. However, it is still possible to alter the constant by using a non-constant pointer to the constant. However you have to make a conscious effort to override constant behaviour.

What is a member function definition inside a class and outside of a class and how are they declared in C plus plus?

Member functions must always be declared inside a class declaration, however they may be defined either inside or outside of the class. A definition is simply the implementation of a function, the code that is executed when the function is called.

When a function is defined inside a class declaration then it is implicitly inline expanded. When it is defined outside of a class declaration, it is not inline expanded but you may explicitly declare it to be inline expanded, if desired. Note that inline expansion should only be utilised when the function has but a few simple statements, preferably just one or two statements at most.

The following example demonstrates the definition of a typical class accessor (a getter) defined within a class declaration (where inline expansion is implied and desired):

class A {

public: int get_data()const{return(m_data);}

private: int m_data;

};

The following example shows the same function defined outside of the class. This time the function will not be inline expanded.

class A {

public: int get_data()const;

private: int m_data;

};

int A::get_data()const{return(m_data);}

Note that the definition may appear in a different file. Generally, classes are designed with a header file and a source file, where the header contains the declarations and the source contains the definition. The source file must include the header file.

Since it is often desirable to inline expand simple class accessors that merely return values, the inline keyword can be used when the definition is external to the class declaration, like so:

class A {

public: inline int get_data()const;

private: int m_data;

};

int A::get_data()const{return(m_data);}

Note that declaring a function inline (implicitly or explicitly) is no guarantee that it will actually be inline expanded, you are merely signalling to the compiler that the function is a candidate for expansion. The compiler is still free to veto the promotion if its inline optimisers deem that such an expansion would compromise performance due to the increased code size that inline expansion incurs. Functions that are called in only one place in your code, regardless of how complex they are, are generally good candidates for expansion. Although you could manually inline expand such functions, if the function call makes your calling code easier to read and maintain, then it's better to retain the function in your code.

Note also that while some compilers allow you to force an inline expansion (such as Microsoft's __forceinline keyword), effectively bypassing the compiler's optimisers, this should be done sparingly as the increased code size can easily outweigh any performance gained by removing the function call. Also note that some functions cannot be inline expanded, even by force. In particular, the compiler cannot inline expand any of the following:

  • a function with a variable argument list.
  • a recursive function (see * note below).
  • a function compiled for debug builds.
  • where the function and the caller use different types of exception handling.
  • a function that uses inline assembly (often dependant upon compiler flags).
  • a virtual function that is called virtually rather than directly.
  • indirect calls via function pointers.

* Some recursive functions can be inline expanded up to a predetermined depth, usually 16 calls at most (thereafter, the calls are treated as calls to new instances of the function). The predetermined depth generally cannot be increased, but it can typically be reduced with a pragma.

For more specific information on inline expansion within your compiler or IDE, consult the compiler's documentation regarding the inline keyword.

Rules for function overloading?

It's a way by which you use define the same function for different input types. For example, think about the the operator "+" which in java works for adding integers, floating point numbers and even string concatenation. The way such functionality is achieved is by overloading.

How do you use the conditional statement of turbo c?

#include<stdio.h>

void main()

{

int a=10,b=15;

clrscr();

if(a>b)

printf("%d is the large number",a);

else

printf("%d is the large number",b);

getch();

}

How do you make quiz master in c plus plus programm?

Assuming the quiz is a simple question/answer style quiz, use a map to associate question strings with answer strings. In order to prevent people from simply examining the program resources to get the answers, you should also consider encrypting the map.

For multiple choice quizzes, use a structure containing the question string, a vector of strings for the possible answers and an unsigned integer to identify the correct answer (as an index into the vector).

What is the difference between virtual function and function overriding?

Virtual Functions and Pure Virtual Functions are relevant in the context of class inheritance.

Unlike Virtual Functions, Pure Virtual Functions do not require a body. This implies that when a base class defining such a function is inherited, the derived class must implement that function. Furthermore, the base class becomes abstract; meaning you cannot create an instance of the base class even if a body is implemented for the function. You are expected to derive from abstract classes; only the derived classes that implement all the inherited Pure Virtual functions can be instantiated.

Here are some examples of Virtual and Pure Virtual function signatures:

- Virtual Function: E.g. virtual void myFunction();

- Pure Virtual Function: E.g. virtual void myFunction() = 0;

Explain the purpose of new and delete operator?

The new operator instantiates a named object of a given type while the delete operator destroys an object. The new operator invokes the object's default constructor unless directed to invoke a specific constructor. The delete operator always invokes the object's destructor.

What are c in and c out in c plus plus?

C and C++ are two common languages used for writing programs and getting suitable desired outputs. They are both strongly typed and, like most other languages in widespread use, imperative.

C is a raw procedural language developed in 1969 to operate on UNIX systems; see the related link for an extensive history. It makes use of structures (simple groups of named values), functions, pre-processor macros, and pointers to memory addresses. It includes some built-in functions known as its standard library. The language, along with its libraries, was originally standardized in 1989 and again in 1999.

C++, begun in 1979 and standardized in 1998, is a step above C and intended to improve the language with object-oriented features such as classes, inheritance, polymorphism, etc. It is a super set of C, meaning that most C source is perfectly valid as C++. It is easier than C because of its extra features, but it is also much more complex and learning all its features is a major accomplishment. More Windows applications are written in C++ than C, but if either one provides a DLL file the other can talk to the first.

What is structured analysis all about?

Structured analysis is a set of techniques and graphical tools used by the analyst for applying a systematic approach to systems analysis. The traditional approach focuses on cost/benefit and feasibility analyses, project management, hardware and software selection, and personnel considerations. In contrast, structured analysis uses graphical tools such as Data Flow diagram, data dictionary, structured English, Decision tree, and decision tables. The outcome of structured analysis is a new document, called system specifications, which provides the basis for design and implementation. The primary steps included in structured analysis are: 1. Study affected user areas, resulting in a physical DFD. The logical equivalent of the present system results in a logical DFD. 2. Remove the physical checkpoints and replace them with a logical equivalent, resulting in the logical DFD. 3. Model new logical system 4. Establish man/machine interface 5. Quantify costs and benefits and select hardware. The structured specification consists of the DFDs that show the major decomposition of system functions and their interfaces, the data dictionary documenting all interface flows and data stores on the DFDs, and documentation of the intervals of DFDs through structured English, decision trees, and decision tables.

What is the difference between procedural and structured programming language in vb?

A procedure, or function, is a set of specific instructions executed one after the other. The data was quite separate from the procedures, and the trick in programming was to keep track of which functions called which other functions, and what data was changed. To make sense of this potentially confusing situation, structured programming was created.

The principle idea behind structured programming is as simple as the idea of divide and conquer. A computer program can be thought of as consisting of a set of tasks. Any task that is too complex to be described simply would be broken down into a set of smaller component tasks, until the tasks were sufficiently small and self-contained enough that they were easily understood,which is also called as dividing complex program into separate modules


by kk,burla

Major difference of turbo c and ansi c and its structures?

Turbo C is an earlier C compiler from Borland. ANSI C is the standard for the C programming language. Therefore, the two are different by definition - Turbo C is a computer program, and ANSI C is a specification for a computer program, which can be implemented in various ways. If we rephrase the question as "what are the difference between the C versions as depicted in the ANSI standard and as implemented in Turbo C?" I would say that most are PC-specific such as the use of far pointers.

What is the best programming language to make an MMORPG with?

There are many options; the best language is probably the one you know best. Some languages may be better than others, but no language is inherently superior to all others, whether you want to make an MMORPG, or any other task.

Which is the unary operator used to dereference a pointer and return the value stored in it?

The asterisk (*) operator dereferences a pointer and returns the value stored in the memory pointed to by the pointer.

C plus plus program to generate Fibonacci series?

#include<stdio.h>

#include<conio.h>

main()

{

int a=0,b=1,c,i,n;

clrscr();

printf("enter the limit of series\n");

scanf("%d",&n);

if(n==0)

printf("%d\n",a);

else

printf("%d\n%d\n",a,b);

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

{

c=a+b;

printf("%d\n",c);

a=b;

b=c;

}

getch();

}

Using function program to multiply two matrix in c plus plus?

#include<iostream>

#include<vector>

#include<exception>

#include<assert.h>

#include<time.h>

class matrix

{

private:

size_t m_rows;

size_t m_cols;

std::vector<std::vector<int>> m_data;

public:

matrix (const size_t rows, const size_t cols);

size_t rows() const { return m_rows; }

size_t cols() const { return m_cols; }

std::vector<int>& operator[] (const size_t index) { return m_data[index]; }

const std::vector<int>& operator[] (const size_t index) const { return m_data[index]; }

std::vector<int>& row (const size_t index) { return m_data[index]; }

const std::vector<int>& row (const size_t index) const { return m_data[index]; }

std::vector<int> col (const size_t index);

const std::vector<int> col (const size_t index) const;

void randomise();

};

void matrix::randomise()

{

for (size_t r=0; r<rows(); ++r)

{

for (size_t c=0; c<cols(); ++c)

{

row(r)[c] = rand() % 9 + 1;

}

}

}

std::ostream& operator<< (std::ostream& os, const matrix& m)

{

for (size_t row=0; row<m.rows(); ++row)

{

for (size_t col=0; col<m.cols(); ++col)

{

os << m[row][col] << '\t';

}

os << std::endl;

}

os << std::endl;

return os;

}

matrix::matrix (const size_t rows, const size_t cols)

: m_rows (rows)

, m_cols (cols)

, m_data ()

{

if (!m_cols !m_rows)

throw std::out_of_range ("matrix: dimensions must be non-zero!");

for (size_t row=0; row<m_rows; ++row)

m_data.push_back (std::vector<int>(m_cols));

}

std::vector<int> matrix::col (const size_t index)

{

std::vector<int> column(m_rows);

for (size_t r=0; r<m_rows; ++r)

column[r] = row(r)[index];

return column;

}

const std::vector<int> matrix::col (const size_t index) const

{

std::vector<int> column(m_rows);

for (size_t r=0; r<m_rows; ++r)

column[r] = row(r)[index];

return column;

}

matrix operator* (const matrix a, const matrix b)

{

if (a.cols() != b.rows())

throw std::out_of_range("matrix operator* : row/column mismatch!");

matrix result (a.rows(), b.cols());

for (size_t r=0; r<a.rows(); ++r)

{

for (size_t c=0; c<b.cols(); ++c)

{

result[r][c]=0;

const std::vector<int>& Row = a[r];

const std::vector<int> Col = b.col(c);

assert (Row.size() == Col.size());

for (size_t index=0; index<Row.size(); ++index)

result[r][c] += (Row[index]*Col[index]);

}

}

return result;

}

int main()

{

srand((unsigned)time(nullptr));

matrix a (3,4);

a.randomise();

std::cout << "Matrix A:\n\n" << a << std::endl;

matrix b (4,5);

b.randomise();

std::cout << "Matrix B:\n\n" << b << std::endl;

std::cout << "Matrix A * B:\n\n" << a * b << std::endl;

}

What happens when raised exception is not caught by catch block?

A non-caught exception is propagated out of the local catch block into the next catch block, daisy chaining to the outermost catch block in the run-time library, where it will be handled by abending the program.

Why we use extension as cpp in c plus plus programs?

Source files use a .cpp file extension, while headers use .hpp. However, this is merely a convention. Most C++ programmers use .h for all headers, even though this convention implies a C-style header rather than a C++ header. Ultimately, the extension is immaterial. If the file can be included in other files, then it is a header, otherwise it is a source file.